egret中三种单利的写法。


1 普通的单例写法

缺点:每个单例类里都要写instance和getInstance。

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写法

优点:不需要使用getInstance,调用更简单

缺点:外部不能直接调用属性,只能调用方法

module Single {
    var name:string = "Test2";
    
    export function run(){
        console.log(name);
    }
}

//使用
Single.run();

 3 继承BaseClass

优点:继承后不用写instance和getInstance。

缺点:getInstance()返回值是any!!导致无法用"."号访问其public属性和方法。

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();

相关