How to define Singleton in TypeScript

前端 未结 20 723

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

    This is probably the longest process to make a singleton in typescript, but in larger applications is the one that has worked better for me.

    First you need a Singleton class in, let's say, "./utils/Singleton.ts":

    module utils {
        export class Singleton {
            private _initialized: boolean;
    
            private _setSingleton(): void {
                if (this._initialized) throw Error('Singleton is already initialized.');
                this._initialized = true;
            }
    
            get setSingleton() { return this._setSingleton; }
        }
    }
    

    Now imagine you need a Router singleton "./navigation/Router.ts":

    /// 
    
    module navigation {
        class RouterClass extends utils.Singleton {
            // NOTICE RouterClass extends from utils.Singleton
            // and that it isn't exportable.
    
            private _init(): void {
                // This method will be your "construtor" now,
                // to avoid double initialization, don't forget
                // the parent class setSingleton method!.
                this.setSingleton();
    
                // Initialization stuff.
            }
    
            // Expose _init method.
            get init { return this.init; }
        }
    
        // THIS IS IT!! Export a new RouterClass, that no
        // one can instantiate ever again!.
        export var Router: RouterClass = new RouterClass();
    }
    

    Nice!, now initialize or import wherever you need:

    /// 
    
    import router = navigation.Router;
    
    router.init();
    router.init(); // Throws error!.
    

    The nice thing about doing singletons this way is that you still use all the beauty of typescript classes, it gives you nice intellisense, the singleton logic keeps someway separated and it's easy to remove if needed.

提交回复
热议问题