使用typescript
/javascript
,我构建了一个单态集合。
然而,在尝试重构和抽象实现时,我试图准备一个类,该类将实现该单例逻辑并供它们扩展。这显然是我的天真,因为这种情况会导致构造函数的问题,而且似乎是不可行的。
因此,我的问题是,是否可以在类/对象的集合上优雅地应用singleton行为?
在下面的代码中,出于可读性考虑,最好抽象掉单例逻辑。此外,特别是,我想强制这个集合中的其他类,因为它们是由贡献者添加的,将它们实现为singleton。如果只是";插入";一些抽象的扩展类或某种包装器。
class Car {
/* Singleton Implementation Start */
private static _instance: Car;
private constructor() {}
public static getInstance(): Car {
if (!Car._instance) {
Car._instance = new Car();
}
return Car._instance;
}
/* Singleton Implementation End */
private _name = "Audi"
private _color = 'red';
private _maxSpeed = 150;
drive(){
console.log(`WOW! You are riding your cool ${this._color} ${this._name} at ${150} kmh!` )
}
paint(color: string){
this._color = color;
}
}
class Plane {
/* Singleton Implementation Start */
private static _instance: Plane;
private constructor() {}
public static getInstance(): Plane {
if (!Plane._instance) {
Plane._instance = new Plane();
}
return Plane._instance;
}
/* Singleton Implementation End */
private _motors = 4;
private _maxSpeed = 550;
fly(){
console.log(`WOW! You are flying your plane with roaring ${_motors} motors at ${150} kmh!` )
}
}
如果我们创建一个接受泛型的工厂函数:
function Singleton<T>() {
return class Singleton {
static instance: T; // must be public
protected constructor() {}
public static getInstance(): T {
if (!this.instance) this.instance = new this() as T;
return this.instance;
}
}
}
然后我们可以扩展返回的类,并将泛型提供为类本身:
class Car extends Singleton<Car>() {
private _name = "Audi"
private _color = 'red';
private _maxSpeed = 150;
drive(){
console.log(`WOW! You are riding your cool ${this._color} ${this._name} at ${150} kmh!` )
}
paint(color: string){
this._color = color;
}
}
这必须用函数来完成,因为静态成员不能引用类的类型参数。此外,一个缺点是你不能有任何私人或受保护的成员。
游乐场