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