I was exploring the singleton design pattern, I have developed a class...
public class SingletonObject {
private static SingletonObject ref;
private SingletonObject () { //private constructor
}
public static synchronized SingletonObject getSingletonObject() {
if (ref == null)
ref = new SingletonObject();
return ref;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException ();
}
}
but synchronization is very costly , so I move to new design of eagerly created instance rather than a lazily created one..
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return uniqueInstance;
}
}
But please advise me how the second design is advantage over the previous design..!!