class IOCContainer {
private mInstances: Map<string, any> = new Map<string, any>()
Register<T extends {}>(instance: T) {
let name = instance.constructor.name
if (!this.mInstances.has(name)) {
this.mInstances.set(name, instance)
} else {
this.mInstances.set(name, instance)
}
}
Get<T extends {}>(type: { new(): T }): T {
let name = type.name
if (this.mInstances.has(name)) {
return this.mInstances.get(name)
} else {
return null;
}
}
}
interface IA { }
class ClassA implements IA { }
let mContainer = new IOCContainer()
mContainer.Register(new ClassA())
mContainer.Get(ClassA)//这个已经可以了
mContainer.Get(IA)//语法编译不通过
如题,想根据类获取对象,这点(抄了cocos的type: { new(): T })实现了,但是不知道怎么实现根据接口获取对象。或者说不知道怎么用接口拿到一个值。
希望达成的效果是,如果一个类继承了接口,可以用这个类拿到对象,也可以根据接口拿到对象。现在我是用类名作为key存在map里,是不是要用其他方式。
那如果两个类都继承同一个接口你怎么通过接口名来获取?