Which of the following code options implements the Singleton pattern correctly?
a class Main {//from w w w . j a v a 2 s . c o m private static Main instance = null; private Main() {} public static Main getInstance() { instance = new Main(); return instance; } } b class Main { private static Main instance = new Main(); public static Main getInstance() { return instance; } } c class Main { private static Main instance = new Main(); private Main() {} private static Main getInstance() { return instance; } } d class Main { private static Main instance; public static Main getInstance() { if (instance == null) instance = new Main(); return instance; } } e None of the above
e
Option (a) is incorrect.
It creates a new object of class Main, whenever method getInstance()
is called.
On the contrary, the Singleton pattern creates only one instance of a class.
Option (b) is incorrect.
A Singleton should define a private constructor so that no other class can create its objects.
The class defined in this option doesn't define any constructor.
In the absence of a constructor, the Java compiler creates a default constructor for a class with the access modifier as that of the class itself.
Because the class in this option is defined with default or package access, a constructor with default access will be created for it by the Java compiler.
Because other classes can use its constructor to create new objects of this class, it doesn't qualify as a Singleton.
Option (c) is incorrect.
There is no way to access an object of class Main outside the class itself.
Variable instance is a static private variable, so it can't be accessed directly.
The constructor of the class is marked private, so it can't be used to create objects of this class.
Method getInstance()
is also private, so no other class can call it.
Option (d) is incorrect.
Though the variable instance is private, and method getInstance()
creates and returns an object of class Main, the catch here is that this class doesn't define a constructor.
As mentioned in the explanation of option (b), in the absence of a constructor, the Java compiler creates a default constructor.
Because other classes can use its constructor to create new objects of this class, it doesn't qualify as a Singleton.