案例
// 定义抽象类的接口
interface AbstractClassInterface {
test(): void;
}
// 抽象类
abstract class AbstractClass implements AbstractClassInterface {
time: 1;
abstract test(): void;
}
// 子类1
class Class1 extends AbstractClass implements AbstractClassInterface {
constructor() {
super();
}
test(): void {
throw new Error("Method not implemented.");
}
test1() {}
}
// 子类2
class Class2 extends AbstractClass implements AbstractClassInterface {
constructor() {
super();
}
test(): void {
throw new Error("Method not implemented.");
}
test2() {}
}
// 子类3
class Class3 extends AbstractClass implements AbstractClassInterface {
constructor() {
super();
}
test(): void {
throw new Error("Method not implemented.");
}
test3() {}
}
// 储存未实例化的类
const map = new Map<string, new () => AbstractClassInterface>([
["class1", Class1],
["class2", Class2],
["class3", Class3],
]);
// 读取类
let ClassConstructor = map.get("class2");
// 实例化类
if (ClassConstructor) {
let instance = new ClassConstructor();
}
网友评论