mercredi 25 février 2015

Java Singleton Design Pattern implementation

Can the implementation for a Singleton class can be as simple as below :



public class MyClass {
private final static MyClass myClass = new MyClass();
public static MyClass getInstance() {
return myClass;
}
}


Over :



public class MyClass {
private final static MyClass myClass;
public static MyClass getInstance() {
if(null == myClass) {
myClass = new MyClass();
}
return myClass;
}
}


Which is the better of the above implementations & why?


One thing that I observed is for the first implementation above the object constructor gets called before the static block if any.


Also if there is a thread-safe version of the 2nd implementation (may be a double null check and synchronized block), which should be preferred ?


Aucun commentaire:

Enregistrer un commentaire