How to define Singleton in TypeScript

前端 未结 20 782

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

    The following approach creates a Singleton class that can be used exacly like a conventional class:

    class Singleton {
        private static instance: Singleton;
        //Assign "new Singleton()" here to avoid lazy initialisation
    
        constructor() {
            if (Singleton.instance) {
                return Singleton.instance;
            }
    
            this. member = 0;
            Singleton.instance = this;
        }
    
        member: number;
    }
    

    Each new Singleton() operation will return the same instance. This can however be unexpected by the user.

    The following example is more transparent to the user but requires a different usage:

    class Singleton {
        private static instance: Singleton;
        //Assign "new Singleton()" here to avoid lazy initialisation
    
        constructor() {
            if (Singleton.instance) {
                throw new Error("Error - use Singleton.getInstance()");
            }
            this.member = 0;
        }
    
        static getInstance(): Singleton {
            Singleton.instance = Singleton.instance || new Singleton();
            return Singleton.instance;
        }
    
        member: number;
    }
    

    Usage: var obj = Singleton.getInstance();

提交回复
热议问题