如何知道什么类继承是来自数据库的对象



我有一个基类,用作其他类的蓝图。 这些类的数据存储在 SQL 数据库中,并在需要时加载。 问题是我如何知道哪个数据库对象对应于哪个类。

所以我有一个动物类和另外 2 个类(猫和狗)扩展了一个动物类。 Dog 和 Cat 类将具有基类具有的所有属性,但它们可以保存不同的方法/函数。 数据库仅存储这些类的数据。现在的问题是,当需要加载这些数据时,系统如何判断是否应该创建狗或猫类?

下面是一些示例代码

const database_data = { name: "test", strength: 10 };
class Animal {
public name: string;
protected strength: number;
constructor(name: string, strength: number) {
this.name = name;
this.strength = strength;
}
get getStrength(): number {
return this.strength;
}
}
class Dog extends Animal {
constructor(name: string, strength: number) {
super(name, strength);
}
wuf(): void {
console.log(`Dog ${this.name} says wuf. Strength: ${this.strength}`);
}
}
class Cat extends Animal {
constructor(name: string, strength: number) {
super(name, strength);
}
miau(): void {
console.log(`Cat ${this.name} says miau. Cat is not strong ;)`);
}
}
//Loading animals from database....
// const loadedAnimal = new Dog/Cat? how do I know(database_data.name, database_data.strength);
// console.log(loadedAnimal);

为了不被迫进行基于if...elseswitch...case的维护..."我需要为每个案例手动制作ifs。if(class === 'dog') new Dog(...)等等。– 科斯塔">...OP 可以采用嵌入到species感知工厂函数中的基于ObjectMap查找方法......

// the OP's refactored (typescript to es-6) class/subtype system.
class Animal {
#strength;
constructor({ species = '', name = '', strength = 0 }) {
Object.assign(this, { species, name });
this.#strength = strength;
}
get strength() {
return this.#strength;
}
valueOf() {
return {
species: this.species,
name: this.name,
strength: this.#strength,
};
}
toJSON() {
return this.valueOf();
}
}
class Dog extends Animal {
constructor(animalData = {}) {
super({ species: 'dog', ...animalData });
}
wuf() {
console.log(`Dog ${ this.name } says wuf. Strength: ${ this.strength }`);
}
}
class Cat extends Animal {
constructor(animalData = {}) {
super({ species: 'cat', ...animalData });
}
miau() {
console.log(`Cat ${ this.name } says miau. Cat is not strong ;)`);
}
}

// (lookup table based) factory function.
function createSpecies({ species = '', ...animalData }) {
const Species = ({ // object-based species-lookup.
cat: Cat,
dog: Dog,
'': Animal
})[species];
return (typeof Species === 'function')
? new Species(animalData)
: null;
}

// helper function for exposing a value's (internal) class name.
function getClassName(value) {
const regXClassName =
// ... [https://regex101.com/r/flUvPh/1]
(/classs+(?<customName>[^s{]+)(?:s+extendss+S+)?s*{|functions+(?<builtInName>[^s(]+)s*(/);
let customName, builtInName;
if ((value ?? null) !== null) {
({ customName, builtInName } = regXClassName
.exec(String(Object.getPrototypeOf(value).constructor)).groups ?? {});
}
return customName || builtInName || (/[objects+(?<className>[^]]+)]/)
.exec(Object.prototype.toString.call(value))
?.groups.className;
}

const dbItems = [{
species: 'cat',
name: 'Spot',
strength: 20,
}, {
species: 'dog',
name: 'Hazel',
strength: 30,
}, {
name: 'test',
}];
const speciesList = dbItems.map(createSpecies);
console.log({
dbItems,
animalClasses: speciesList.map(getClassName),
animalValues: speciesList.map(species => species.valueOf()),
animalJSONs: speciesList.map(species => JSON.stringify(species)),
});
const [ cat, dog ] = speciesList;
cat.miau();
dog.wuf();
.as-console-wrapper { min-height: 100%!important; top: 0; }

最新更新