What is Singleton Design Pattern

Singleton Design Pattern ensures that maximum one object can exist for a class. Below are steps you need to make a class Singleton.

1. Make all constructors private.
2. Add a static method, which creates and returns object of the class.
3. Add a static data member of its type, so that it can be returned, if object already exists.
4. Add a static int data member, which stores number of objects currently exists(whose value will be either 0 or 1, always)
5. In static method(added above in step 2), if number of objects is zero, create new object(by invoking private constructor), and return it. If number of objects is one, return existing object, without creating new object.

Below is example Design pattern code.
public class Abc {

private static int objCount = 0;

//step 3
private static Abc obj;

//step 1
private Abc(){ System.out.println(“This is Constructor”);}

//step 2
public static Abc createInstance(){
if(objCount ==0)
{
objCount++;
obj= new Abc();
System.out.println(“object created”);
}
else
{
System.out.println(“Returning existing object”);
}

return obj;
}

}

public class MySingleton {
public static void main(String[] args) {

Abc nc = Abc.createInstance();
Abc nc1 = Abc.createInstance();
Abc nc2 = Abc.createInstance();
}
}

Output:
object created
Returning existing object
Returning existing object

3 thoughts on “What is Singleton Design Pattern”

Leave a Reply