Yes we can clone the singleton class object. Let´s see following example:
public class Singleton implements Cloneable{
public static Singleton singleton;
public static Singleton getSingleton(){
if(singleton==null){
singleton=new Singleton();
}
return singleton;
}
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public static void main(String[] args) {
Singleton singleton=Singleton.getSingleton();
System.out.println(singleton);
try{
System.out.println((Singleton)singleton.clone());
}
catch (Exception e) {
// TODO: handle exception
}
}
}
Output:
---------------------------
Singleton@e48e1b
Singleton@12dacd1
It´s printing the different different object. If you want to prevent the cloning just throw some exception in overridden clone method.
|