samedi 2 juin 2018

Design Pattern special case

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 LazySingalton implements Cloneable{

private static LazySingalton lazy;
private static int counter=0;
private LazySingalton() {
    System.out.println(counter++);
}

public synchronized static LazySingalton getObject(){
    if(lazy==null)
        lazy=new LazySingalton();
    return lazy;
}

@Override
protected Object clone() throws CloneNotSupportedException {

    return super.clone();
}

public class DriverClone {

public static void main(String[] args) throws CloneNotSupportedException {
    LazySingalton obj=LazySingalton.getObject();

    System.out.println(obj);
    System.out.println(obj.clone());
}

}

Output

0

LazySingaltonDesignePattern.LazySingalton@157ee3e5 LazySingaltonDesignePattern.LazySingalton@3da3da69

Aucun commentaire:

Enregistrer un commentaire