While we are creating a class using Singleton Pattern I am able to clone in the same class.
It means the Singleton Pattern rule was violated. Can any one please clarify my doubt.
My Code is:
class SingletonObject implements Cloneable
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
SingletonObject obj = null;
if (ref == null){
// it's ok, we can call this constructor
ref = new SingletonObject();
try {
obj = (SingletonObject)ref.clone();
if(obj.equals(ref)){
System.out.println("both objects are same");
}else{
System.out.println("both objects are not same");
}
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return obj;
}
private static SingletonObject ref;
}
Good observation. Your code is a good example of why many Java developers consider
clone()to be problematic:It is a mechanism which circumvents many restrictions that you can place on the creation of objects. It can thus be used to duplicate singletons. This is (arguably) a design flaw of Java. The only solution is to not use
clone, or not to implement a publicclone()method in your class.In practice it’s not much of a problem, because
clonewill only work if the class explicitly implements it, which you would not do for a singleton. It’s still ugly though.