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.
-
3You use a dress (design) pattern to make a dress. The object is the dress. – Peter Lawrey Jun 10 '16 at 13:25
3 Answers
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.

- 1,506
- 13
- 35
Singleton Pattern is a map of a route. Singleton Object is actually going through that route.
And you can drive, walk, and run through that route. If you drive, you can use car, truck (or) any other means.
Same way Single Pattern is a way (or) method of doing something. You can use any language, computer (or) platform to actually implement that Singleton Object.

- 3,654
- 13
- 17
Singleton_design_pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
Singleton object is a single object, which has been created by implementing Singleton approach.
To achieve this ( TRUE Singleton) ,
- Make sure that your class is
final
. Others can't sub-class it and create one more instance - Make your singleton object as
private static final
- Provide
private
constructor and publicgetInstance()
method. - Make sure that this Singleton class is loaded by one
ClassLoader
only - override
readResolve()
method and return same instance.
Refer to this SE question too for efficient implementation of Singleton
.
What is an efficient way to implement a singleton pattern in Java?

- 1
- 1

- 37,698
- 11
- 250
- 211