In Singleton design pattern if I create clone of my singleton class object, and printing both the object, I'm getting two different output but constructor being called only once. I'm confused, weather Singleton design pattern fails in such cases or its just a illusion?
public class LazySingleton implements Cloneable{
private static LazySingleton lazy;
private static int counter=0;
private LazySingleton() {
System.out.println(counter++);
}
public synchronized static LazySingleton getObject(){
if(lazy==null)
lazy=new LazySingleton();
return lazy;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public class DriverClone {
public static void main(String[] args) throws CloneNotSupportedException {
LazySingleton obj=LazySingleton.getObject();
System.out.println(obj);
System.out.println(obj.clone());
}
}
Output
0
LazySingletonDesignPattern.LazySingleton@157ee3e5
LazySingletonDesignPattern.LazySingleton@3da3da69