1 普通的單例寫法this
缺點:每一個單例類裏都要寫instance和getInstance。spa
class Single{ private static instance:Single; public static getInstance():Single{ if(this.instance == null){ this.instance = new Single(); } return this.instance; } public run(){ } } //使用 Single.getInstance().run();
2 Module寫法code
優勢:不須要使用getInstance,調用更簡單blog
缺點:外部不能直接調用屬性,只能調用方法繼承
module Single { var name:string = "Test2"; export function run(){ console.log(name); } } //使用 Single.run();
3 繼承BaseClassget
優勢:繼承後不用寫instance和getInstance。string
缺點:getInstance()返回值是any!!致使沒法用"."號訪問其public屬性和方法。io
class BaseClass { public static getInstance():any { var Class:any = this; if (!Class._instance) { Class._instance = new Class(); } return Class._instance; } } class Single extends BaseClass{ public run(){ } } //使用 Single.getInstance().run();