Singleton Design Pattern

The singleton pattern is a simple design trick. Imagine you have a special class, and you only want one copy of it. For example, think about having just one toolbox that lots of workers share, instead of giving each worker their own toolbox. This is helpful because making lots of toolboxes can be expensive.

This idea works in software too. Sometimes, we only want one instance of a class. Like having just one connection to a database that many parts of a program can use. It's like having a single manager for problems, rather than many managers. This is what the singleton pattern does – it makes sure we only create one of these special classes.

Implement Singleton Pattern In TypeScript

Imagine we're working on a project and we want to control the overall state of the project from a single location. In this situation, we can utilize the singleton design pattern.

class ProjectState{
    private static instance: ProjectState;

    // private constructor to force use of
    // getInstance() to create Singleton object
    private constructor(){}

    static getInstance(){
        if(this.instance){
            return this.instance;
        }
        this.instance = new ProjectState();
        return this.instance;
    }
}

In TypeScript, we've defined the getInstance() method as static, allowing us to access it without needing to create an instance of the class. When we call getInstance() for the first time, it generates a new singleton object. Subsequent calls to getInstance() provide the same object as before. It's worth noting that the Singleton object isn't generated until we explicitly require it by calling getInstance(). This approach, where the object is created only when needed, is referred to as lazy instantiation.


THANKS FOR READING❤