Singleton pattern ensures “a class has only one instance”. The purpose of the pattern is to limit the object creations where only one object suffice to cater the need.
How could we implement singleton pattern: We need to define private constructor so that no outside class could possible create an object. Define static method to create an instance of the class which allows other classes to access the only object.
package truecode.designpattern;
public class Singleton {
private int data;
private static Singleton singleton;
//one time initialization goes here,
//private constructor makes sure no outsider class can instantiate it.
private Singleton() {
data = 10;
}
//define static method to access the only object
public static Singleton getInstance() {
if (singleton==null) {
singleton = new Singleton();
}
return singleton;
}
public int getData() {
return singleton.data;
}
//setter goes here...
}
Note: Above class uses Singleton pattern to expose it’s only object.
package truecode.designpattern;
public class SingletonTest {
public static void main(String ...a) {
System.out.println("Value of data "+Singleton.getInstance().getData());
}
}
Before you go ahead and execute the program, just pause for a while and ponder.. is there a way we can possibly create another object of this class… I guess so.
Feel free to comment.