Preventing cloning of Object in while using singleton design pattern
Hi All,
Using singleton design pattern is a best way to access a valuable resource. In this case we do use Singleton design pattern and stops clients classes to create multiple instances of the Class.
But there is a loophole in this pattern and one can create instance of the Singleton class using object cloning.
So we should prevent cloning of object in this class as well if required.
Code given below gives a brief idea of how to stop client class to clone an object.
package com.sun;
/** * @author Sunil Chauraha */
class Clone1 implements Cloneable{
@Override protected Object clone() throws CloneNotSupportedException
throw new CloneNotSupportedException(“Cloning of this class is not supported by me…”);
}
public class CloneTest {
public static void main(String[] args) {
try{
Clone1 clone1 = new Clone1();
Clone1 clone2 = (Clone1)clone1.clone();
}catch (CloneNotSupportedException e) {
System.err.println(e.getMessage()+”: “+e);
}
}
}
No trackbacks yet.