...
Wiki Markup |
---|
To address the cloning issue, do not make the _Singleton_ class cloneable. If it indirectly implements the {{Cloneable}} interface through inheritance, override the object's {{clone}} method and throw a {{CloneNotSupportedException}} exception from within it. \[[Daconta 03|AA. Java References#Daconta 03]\] |
Code Block | ||
---|---|---|
| ||
class MySingleton {
private static MySingleton _instance;
private MySingleton() {
// construct object . .
// private constructor prevents instantiation by outside callers
}
// lazy initialization
public static synchronized MySingleton getInstance() {
if (_instance == null) {
_instance = new MySingleton();
}
return _instance;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
// Remainder of class definition . . .
}
|
See MSC05-J. Make sensitive classes noncloneable for more details about restricting the clone()
method.
Noncompliant Code Example
When the utility of a class is over, it is free to be garbage collected. A dynamic reference can however, cause another instance of the Singleton class to be returned. This behavior can be troublesome when the program needs to maintain only one instance throughout its lifetime.