Saturday, April 7, 2012

Can we clone a Singleton object?

This might seem a tricky question, can we use object.clone() to create a new object of the class and break our Singleton pattern.

Well the answer to this is NO.

The clone method has protected access on the Object class - meaning it is available in the Object class and to the extending classes (which is our Singleton class). Thus any attempt to invoke clone() method on any object will give compile time exception.

This is illegal:-
SingletonClass instance = SingletonClass.getInstance();
SingletonClass newInstance = (SingletonClass)instance.clone();

Hence to create a clone of an object, the object must override the clone() method of the Object class. Thus our SingletonClass can only be cloned if it explicitly implements the clone() method.

No comments:

Post a Comment