因为 TS 的语法,泛型类的 T 不能用于 static 方法,所以用泛型函数去实现。
又不想因为调用 getInstance 在用 <> 传个类型,所以在子类封装一个 get instance。
这样代码跳转也是直接跳到对应的子类而不是父类
export class Singleton {
protected constructor() {}
private static _instance: any;
protected static getInstance<T extends Singleton>(): T {
if (!this._instance) {
this._instance = new this();
}
return this._instance;
}
public static deleteInstance() {
if (this._instance) {
delete this._instance;
}
}
}
export class UserMgr extends Singleton {
public static get instance() {
return super.getInstance<UserMgr>();
}
}
