The most common example of a Singleton class in a single threaded environment is below:
{
private static Singleton obj;
// private constructor to force use of
// getInstance() to create Singleton object
private Singleton() {}
public static Singleton getInstance()
{
if (obj==null)
obj = new Singleton();
return obj;
}
}
As per my understanding the following can also be considered a Singleton, isn't it?
public class SingleTon {
static SingleTon s;
SingleTon getInstance() {
if (s == null) {
s = new SingleTon();
}
return s;
}
public static void main(String[] args) {
SingleTon s1 = new SingleTon();
s1 = s1.getInstance();
SingleTon s2 =new SingleTon();
s2 = s2.getInstance();
}
}
The difference in the second case is, I am not adding a private constructor and even though 2 different instances got created initially, by reassigning the value of getInstance
, we are making the instances use the same object.
Please let me know if my understanding is correct.
CodePudding user response:
For Single threaded env your first class is singleton but not second one.
For a singleton class, there must exist only a single object inside JVM but in your second case you haven't made constructor as private so by default at compile time compiler will add default public constructor and this will break the rule of singleton because whenever you will call new Singleton()
, it will return a new instance so there is no meaning of having getInstance
method with public constructor.
For a singleton class private constructor is must so that it cant be initialised from outside the class.
CodePudding user response:
Second one is not Singleton, constructor must be private for singleton class.
You can use early initialisation as well to create singleton class -
{
private static Singleton obj = new Singleton();
private Singleton() {}
public static Singleton getInstance()
{
return obj;
}
}