Singleton

Used when you want to maintain only one instance of something in the application. (Like DB instance, socket, etc)

It does this by making the constructor private, so that only ONE static method (like getInstance()) from the class can call it, ONLY ONCE to instantiate it.

circle-info

This helps so that you do not need to pass these classes by parameters to dependency inject them.

triangle-exclamation
class MyClass {
    private someProp: any;
    static instance: MyClass;
    
    private constructor (){}
    
    doSomething() {
        return this.someProp;
    }
    
    static getIntance() {
        if (!MyClass.intance) MyClass.instance = new MyClass();
        return MyClass.instance;
    }
}

On the outside you just call the getInstance() before using the Class.

Last updated