shrini1000 shrini1000 - 5 months ago 18
Java Question

Singleton design pattern and preventing cloning

Many articles I've read on the Net about Singleton design pattern mention that the class should override 'clone()' method and in it, throw 'CloneNotSupported' exception. Is this really necessary?

The clone() method by default is protected, so no class (except those in the same package) would be able to call it on that Singleton instance. Plus, if this Singleton does not implement Cloneable, then even if this method is called, it will give a runtime exception. Plus, the constructor being private, we won't be able to subclass it and thus allow for its cloning. So should I still implement this advice for my Singleton classes?

EDIT: Just to clarify: I'm not looking for the best possible way to implement Singleton. I'm just asking about the validity of the advice mentioned above, w.r.t the 'normal' Singleton pattern (and not Enum based Singleton).

Answer

If you're really going to implement a singleton, use a one-element enum and stop thinking about it.


EDIT: Just to clarify: I'm not looking for the best possible way to implement Singleton. I'm just asking about the validity of the advice mentioned above, w.r.t the 'normal' Singleton pattern (and not Enum based Singleton).

Since you have Effective Java, then you should already be aware of the pitfalls and problems with Cloneable. That said, if you're going to implement a singleton one of the "wrong" ways, no, there's absolutely no reason whatsoever to implement Cloneable and override Object#clone() just to throw CloneNotSupportedException. Object#clone() already does this when the Cloneable interface is absent.