Typescript 小工具 ---- 单例通用类

typescript 通用单例类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
export function Singleton<E>() {
    class SingletonE {
        protected constructor() {}
        private static _ins: SingletonE = null;
        public static get Ins(): E {
            if (SingletonE._ins == null) SingletonE._ins = new this();
            return SingletonE._ins as E;
        }
    }
    return SingletonE;
}

使用方式

1
2
3
4
5
export class Game extends Singleton() {
    isText: boolean = false;
}

console.log(Game.Ins.isText);