Tag Archives: singleton

Using Clone with Singleton pattern

A friend came up with an interesting question today. Can we clone the singleton class object? Practically it is of no value, but theoretically the question is interesting. Practically not useful, because why would someone want to make the singleton class cloneable? The whole concept of singleton class is to avoid creation of multiple objects for a class.

But the question do bring up interesting concept. Can we clone a singleton object? As we know every class inherits from Object class, which does have a protected method clone. And if we want to make sure that our class’s objects can be cloned, we will need to implement cloneable interface and implement clone method. But then you are actually implementing creation of clones and violating basic principle of single-ton pattern.

A little googling showed that we can actually implement the cloning accidentally. That is, say there is a class X which is clonable and our developer extends this class in the singleton class (why would someone do that?). In that case, our Singleton class do implement clonable, though not intentionally. Though we do not have a clone method for our singleton class, unless we override it. So still we are safe.

Still, if we want to make sure that our singleton class never becomes clonable, a sureshot way to do that is to implement clonable and force an exception if someone do try to clone objec of singleton class, he will get the exception.



public class SingletonTest implements Cloneable{

	private static SingletonTest singletonObject=null;
	private SingletonTest(){
		
	}
	
	public static SingletonTest getInstance()
	{
		if(singletonObject == null)
		{
			return new SingletonTest();
		}
		return singletonObject;
	}
	
	public Object clone() throws CloneNotSupportedException
	{
		throw new CloneNotSupportedException();
		
	}
	
}