Hi folks,
To understand preventing clone while using singleton, I should know to verify the behavior of clone in singleton first..
for this I have created singleton class as follows:
package foo;
public class SingletonObject implements Cloneable{
private static SingletonObject ref;
private SingletonObject(){
System.out.println("Inside the singleton constructor");
}
public static SingletonObject getSingletonObject(){
if(ref==null){
ref=new SingletonObject();
System.out.println("Creating new instance...");
}else{
System.out.println("Old obj...");
}
return ref;
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
//Other code through which I am fetching
package foo;
public class FetchSingletn {
public static void main(
String[] args) throws CloneNotSupportedException {
SingletonObject singletonObj=SingletonObject.getSingletonObject();
singletonObj.getSingletonObject();
SingletonObject clone=(SingletonObject)singletonObj.clone();//line1
clone.getSingletonObject();
if(singletonObj.equals(clone)){
System.out.println(" You created another instance of your singleton !!!");//When this will satusfy???
}
}
/* out put : Inside the singleton constructor
Creating new instance...
Old obj...
Old obj...
*/
My question is to prevent clone how I will be able to recognise and my condition of singleton and clone object equality would get possible..
Your response towards this would be higly appreciated to understand singleton concept of cloning.
Thank you..
Regards,
Brijesh Shah