Which two properly implement a Singleton pattern?
A.
class Singleton {
private static Singleton instance;
private Singleton () {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton ();
}
return instance;
}
}
B.
class Singleton {
private static Singleton instance = new Singleton();
protected Singleton () {}
public static Singleton getInstance () {
return instance;
}
}
C.
class Singleton {
Singleton () {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton ();
}
public static Singleton getInstance () {
return SingletonHolder.INSTANCE;
}
}
D.
enum Singleton {
INSTANCE;
}
Explanation:
A: Here the method for getting the reference to the SingleTon object is correct.
B: The constructor should be private
C: The constructor should be private
Note: Java has several design patterns Singleton Pattern being the most commonly used. Java
Singletonpattern belongs to the family of design patterns, that govern the instantiation process.
This design patternproposes that at any time there can only be one instance of a singleton (object)
created by the JVM.
The class’s default constructor is made private, which prevents the direct instantiation of the object
by others(Other Classes). A static modifier is applied to the instance method that returns the
object as it then makes thismethod a class level method that can be accessed without creating an
object.
OPTION A == SHOW THE LAZY initialization WITHOUT DOUBLE CHECKED LOCKING
TECHNIQUE ,BUT
ITS CORRECT
OPTION D == Serialzation and thraead-safety guaranteed and with couple of line of code enum
Singletonpattern is best way to create Singleton in Java 5 world.
AND THERE ARE 5 WAY TO CREATE SINGLETON CLASS IN JAVA
1>>LAZY LOADING (initialization) USING SYCHRONIZATION
2>>CLASS LOADING (initialization) USINGprivate static final Singleton instance = new
Singleton();
3>>USING ENUM
4>>USING STATIC NESTED CLASS
5>>USING STATIC BLOCK
AND MAKE CONSTRUCTOR PRIVATE IN ALL 5 WAY.
A
B
A (Meets all contracts of Signeton)
D (We can also use Enum to create Sigleton instance)