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).
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.
@shrini1000, You have a valid question but the suggetsion about clone is very specific to following condition
public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
The above is only necessary if a superclass of a singleton class implements a public clone() method.
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