解决ts 中单例 使用时需要传入本身对象的问题
更优雅的使用 单例
export function Singleton<T>() {
class SingletonE {
protected constructor() {
}
private static instance: SingletonE = null;
public static get Instance(): T {
if (SingletonE.instance == null) {
SingletonE.instance = new this();
}
return SingletonE.instance as T;
}
}
return SingletonE;
}
///使用方式
class Test extends Singleton<Test>()
{
public TestGet() : string
{
return "";
}
}
Test.Instance.TestGet();
本文介绍了一种在TypeScript中更加优雅地实现单例模式的方法。通过泛型函数`Singleton`来创建单例类,使得在实例化时无需传递自身对象。这种方式不仅简化了单例模式的使用,还保持了代码的整洁性和易读性。
1349

被折叠的 条评论
为什么被折叠?



