typescript 通用单例类

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;
}

使用方式

export class Game extends Singleton() {
    isText: boolean = false; 
}

console.log(Game.Ins.isText);

标题:Typescript 小工具 ---- 单例通用类
作者:K
地址:https://pala.icu/articles/2021/09/02/1630593040230.html