How to define Singleton in TypeScript

前端 未结 20 732

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

    Another option is to use Symbols in your module. This way you can protect your class, also if the final user of your API is using normal Javascript:

    let _instance = Symbol();
    export default class Singleton {
    
        constructor(singletonToken) {
            if (singletonToken !== _instance) {
                throw new Error("Cannot instantiate directly.");
            }
            //Init your class
        }
    
        static get instance() {
            return this[_instance] || (this[_instance] = new Singleton(_singleton))
        }
    
        public myMethod():string {
            return "foo";
        }
    }
    

    Usage:

    var str:string = Singleton.instance.myFoo();
    

    If the user is using your compiled API js file, also will get an error if he try to instantiate manually your class:

    // PLAIN JAVASCRIPT: 
    var instance = new Singleton(); //Error the argument singletonToken !== _instance symbol
    

提交回复
热议问题