How to implement Singleton in Typescript?
Here is an example of how we implement Singleton in Typescript
/**
* The Singleton class defines an `instance` getter, that lets clients access
* the unique singleton instance.
*/
class Singleton {
static #instance: Singleton;
/**
* The Singleton's constructor should always be private to prevent direct
* construction calls with the `new` operator.
*/
private constructor() { }
/**
* The static getter that controls access to the singleton instance.
*
* This implementation allows you to extend the Singleton class while
* keeping just one instance of each subclass around.
*/
public static get instance(): Singleton {
if (!Singleton.#instance) {
Singleton.#instance = new Singleton();
}
return Singleton.#instance;
}
/**
* Finally, any singleton can define some business logic, which can be
* executed on its instance.
*/
public someBusinessLogic() {
// ...
}
}
Above example is standard way to implement Singleton but it is not safe when working with multiple threads
For thread safe we can use a lock mechanism when getting instance of Singleton