If we are implementing a class as a singleton, we do the following
class Single
{
private Single singleton;
public static Single getInstance()
{
if(null == singleton)
{
singleton = new Single();
}
return singleton;
}
//then we make the constructor private
private Single()
{
}
}
Considering the above, wiil it be a good idea to override clone() as well to prevent multiple instances of the class?
There is no clone() method in the Cloneable interface. As @Ivan points out, if your class does not implement Cloneable then calling Single#clone() will throw a CloneNotSupportedException.
That said, cloning is something that happens infrequently in well-written Java these days. As Josh Bloch writes in Effective Java, Item 11:
The
Cloneableinterface was intended as a mixin interface (Item 18) for objects to advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its primary flaw is that it lacks aclonemethod, andObject's clone method is protected. You cannot, without resorting to reflection (Item 53), invoke theclonemethod on an object merely because it implementsCloneable. Even a reflective invocation may fail, as there is no guarantee that the object has an accessibleclonemethod. Despite this flaw and others, the facility is in wide use so it pays to understand it.
...basically, people don't/shouldn't use clone(). It's a poorly designed interface, and if you want your objects to be cloneable, it's better to provide a copy constructor or copy factory method (code stolen from Item 11):
public Yum(Yum yum); // copy constructor
public static Yum newInstance(Yum yum); // copy factory
And while I'm talking about Effective Java, there's a better way to write a singleton, assuming that you really do need one (which is a big if!).
As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With