0

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
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51

2 Answers2

0

The Singleton pattern is nothing that the JVM provides. The JVM doesn't know anything about a Singleton and that the developer intends it to be present just a single time. It's just a pattern, no built-in JVM feature.

Of course, there are ways to duplicate a Singleton, for instance, using the Reflection API. Nothing would stop a developer to clone your Singleton (in case it's not an enum).

As you posted, the clone() can be used, too. In your sample, you have produced indeed two different objects. However, to prevent cloning, it's more or less common practice to override clone() and throw a CloneNotSupportedException.

Jan B.
  • 6,030
  • 5
  • 32
  • 53
0

The problem arises where you make you singleton cloneable:

public class LazySingleton implements Cloneable

There is no reason to do this for a singleton, since by definition there is only one instance of a singleton.

Don't implement Cloneable, then it can't be cloned (by invoking clone(), at least).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243