• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singelton creation using clone

 
Brijesh shah
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Prashant Saraf
Ranch Hand
Posts: 57
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you only need to overwrite the clone method. and this would look like below


or



And no need to implement Cloneable.
 
Junilu Lacar
Bartender
Pie
Posts: 7747
60
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Please UseCodeTags ← (click)

2. If you don't implement Cloneable, then you inherit the behavior of Object, which means the clone() method will throw a CloneNotSupportedException. In other words, DON'T implement Cloneable if you don't want your class instances to be cloneable.

3. Why would you expect the condition of singleton.equals(clone) to ever be satisfied? It's a SINGLETON -- there should only be one instance of the class.

4. Don't worry about lazy initialization unless your singleton is VERY complicated and is very costly to initialize. Understand the implications of double checked locking before you use the just-won't-die-a-death-it-should-have-died-a-million-times-by-now idiom of:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic