Wednesday, November 14, 2018

TypeScript - Classes - Singleton pattern and private constructors

Singleton Pattern means that you should be able to able to create only one instance of the class.  Consider the below example in which we create a SIngleton class.

// Demo - private constructors - Singleton class
class mySingleton {
private static instance: mySingleton;

private constructor(public name:string) {

}

static getInstance() {
if (!mySingleton.instance) {
mySingleton.instance = new mySingleton("The Singleton Input");
}

return mySingleton.instance;
}
}

// Only One instance
let mySingletonInstance = mySingleton.getInstance();

In this example, we ensure that it is a singleton class by:

  • making the constructor private - hence, the instance cannot be created outside the class
  • Since, the instance of the class is created within the class itself. We can place a check within the class - for creating the Singleton instance only when it is not already created.

Reference:

No comments:

Post a Comment