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.
What is the difference between Singleton Design Pattern and Singleton Object In Java?
1k views Asked by dgupta3091 AtThere are 3 answers
On
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.
On
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
privateconstructor and publicgetInstance()method. - Make sure that this Singleton class is loaded by one
ClassLoaderonly - 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?
You are right, A Singleton Design Pattern is used to instantiate a Singleton Object:
The code would look like this:
To call the SingleObject class:
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.