Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 631
shrini1000 Avatar asked Feb 16 '12 14:02

shrini1000


2 Answers

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.

like image 130
Matt Ball Avatar answered Oct 09 '22 07:10

Matt Ball


@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.

like image 34
Gourabp Avatar answered Oct 09 '22 07:10

Gourabp