方案一
优点:调用无括号,被继承结构简单
缺点:没有语法提示
写法:
namespace Epitome
{export class Singleton{ private static _Instance;static get Instance() { if(!this._Instance)this._Instance = new this();return this._Instance; } }
}用法:
class example extends Epitome.Singleton
{public print() {return "Hello world";}
}调用:
example.Instance.print();
方案二
优点:被继承结构简单,有语法提示
缺点:调用有括号
写法:
namespace Epitome
{export class Singleton{static Instance<T extends {}> (this:new()=>T):T{if(!(<any>this).Instance){(<any>this).Instance=new this();}return (<any>this).Instance;}}
}用法:class example extends Epitome.Singleton
{public print() {return "Hello world";}
}调用:example.Instance().print();
方案三
优点:调用无括号,有语法提示
缺点:被继承结构复杂点
写法:
namespace Epitome
{export function Singleton<T>(){class Singleton {protected constructor() {}private static _Instance: Singleton = null;public static get Instance(): T {if(Singleton._Instance == null){Singleton._Instance = new this();}return Singleton._Instance as T;}}return Singleton;}
}用法:class example extends Epitome.Singleton<example>()
{public print() {return "Hello world";}
}调用:example.Instance.print();
方案四
优点:调用无括号,有语法提示
写法:
namespace Epitome
{export class Singleton {public constructor() {}public static Instance(...param: any[]): any{let Class: any = this;if (!Class._Instance) {Class._Instance = new Class(...param);}return Class._Instance;}}
}用法:class example extends Epitome.Singleton
{public print() {return "Hello world";}
}class SingletonManager
{public static get ExampleManager():example{return example.Instance();}
}调用:SingletonManager.ExampleManager.print();