Category Archives: Singleton Pattern

Singleton Pattern – Design Pattern

A Singleton pattern ensures a class has only instance, and provides a global point access to it.

For detailed overview we can have a look at below code flow, We are having a Singleton class having private constructor, that can’t be instantiated directly by outsider class using new operator. For instantiating this class we need to call class’s method.

public function callProgram () {
    ....
    neededInstance = Singleton.getInsatnce(); // will be returning object of singleton class.
    ....
    ....
}


public class Singleton {
    
    private static Singleton uniqueInstance ;

    //constructor of a class
    private Singleton() {

    }

    public static Singleton getInsatnce() {
        if ( uniqueInstance == null) {
            synchronized (Singleton.class) {
                if ( uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }

        return uniqueInstance;
    }
}