This was the question that was asked to me recently in an interview. According to me, it is through singleton pattern we can instantiate singleton objects. But, I would like to know whether I am right or not.
You are right, A Singleton Design Pattern is used to instantiate a Singleton Object:
SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object. source
The code would look like this:
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject() {
}
//Get the only object available
public static SingleObject getInstance() {
return instance;
}
public void showMessage() {
System.out.println("Hello World!");
}
}
To call the SingleObject class:
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
//show the message
object.showMessage();
}
}
So, the Singleton Design Pattern describes how to use a Singleton Object. WikiLink
Please bear in mind that Singletons are, in fact, global variables in disguise. Thus Singletons are considered to be deprecated.