How to define Singleton in TypeScript

前端 未结 20 729

What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).

20条回答
  •  春和景丽
    2020-11-28 20:28

    i think maybe use generics be batter

    class Singleton{
        public static Instance(c: {new(): T; }) : T{
            if (this._instance == null){
                this._instance = new c();
            }
            return this._instance;
        }
    
        private static _instance = null;
    }
    

    how to use

    step1

    class MapManager extends Singleton{
         //do something
         public init():void{ //do }
    }
    

    step2

        MapManager.Instance(MapManager).init();
    

提交回复
热议问题