Posted By:
Robert_Lybarger
Posted On:
Wednesday, February 21, 2007 11:05 PM
The constructor needn't be "private" ... it could be "protected" to allow subclassing. The main idea is that it just isn't "public". The static bits (the class reference and the initializer/accessor) would, however, need to be recreated in the subclass, as static elements don't inherit. (This being the case, the static class reference could be left private, as it doesn't really matter; leaving it as private is usually a faster clue for someone else reading the code than it also being static.) Consider:
/*SingletonBase.java*/
public class SingletonBase {
private static SingletonBase instance = null;
protected int value;
protected SingletonBase() {
value = 42;
}
public static SingletonBase getInstance() {
if (instance==null) {
instance = new SingletonBase();
}
return instance;
}
public int getValue() {
return value;
}
}
/*SingletonSub.java*/
public class SingletonSub extends SingletonBase {
private static SingletonSub instance = null;
protected SingletonSub() {
super();
value++;
}
public static SingletonSub getInstance() {
if (instance==null) {
instance = new SingletonSub();
}
return instance;
}
}
/*test 'main' method*/
public static void main(String[] args) {
SingletonBase base = SingletonBase.getInstance();
SingletonSub sub = SingletonSub.getInstance();
System.out.println(base.getValue());
System.out.println(sub.getValue());
}
/*output*/
42
43
That being said, I've never really needed to do this -- those classes I've wrapped a singleton pattern around could be marked 'final' for what I've used them for, and therefore I just use 'private' for those variables. Hopefully someone a little more versed in patterns theory could be a bit more informative as to whether a subclass on a 'singleton'ed class is a good idea, or whether some other pattern/concept can help out...?