How to define Singleton in TypeScript

前端 未结 20 754

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:48

    Add the following 6 lines to any class to make it "Singleton".

    class MySingleton
    {
        private constructor(){ /* ... */}
        private static _instance: MySingleton;
        public static getInstance(): MySingleton
        {
            return this._instance || (this._instance = new this());
        };
    }
    

    Test example:

    var test = MySingleton.getInstance(); // will create the first instance
    var test2 = MySingleton.getInstance(); // will return the first instance
    alert(test === test2); // true
    

    [Edit]: Use Alex answer if you prefer to get the instance through a property rather a method.

提交回复
热议问题