How to define Singleton in TypeScript

前端 未结 20 746

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

    Since TS 2.0, we have the ability to define visibility modifiers on constructors, so now we can do singletons in TypeScript just like we are used to from other languages.

    Example given:

    class MyClass
    {
        private static _instance: MyClass;
    
        private constructor()
        {
            //...
        }
    
        public static get Instance()
        {
            // Do you need arguments? Make it a regular static method instead.
            return this._instance || (this._instance = new this());
        }
    }
    
    const myClassInstance = MyClass.Instance;
    

    Thank you @Drenai for pointing out that if you write code using the raw compiled javascript you will not have protection against multiple instantiation, as the constraints of TS disappears and the constructor won't be hidden.

提交回复
热议问题