How to define Singleton in TypeScript

前端 未结 20 763

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条回答
  •  猫巷女王i
    2020-11-28 20:40

    After scouring this thread and playing around with all the options above - I settled with a Singleton that can be created with proper constructors:

    export default class Singleton {
      private static _instance: Singleton
    
      public static get instance(): Singleton {
        return Singleton._instance
      }
    
      constructor(...args: string[]) {
        // Initial setup
    
        Singleton._instance = this
      }
    
      work() { /* example */ }
    
    }
    

    It would require an initial setup (in main.ts, or index.ts), which can easily be implemented by
    new Singleton(/* PARAMS */)

    Then, anywhere in your code, just call Singleton.instnace; in this case, to get work done, I would call Singleton.instance.work()

提交回复
热议问题