是的,这在技术上是可行的,因为单例是一种设计模式,而不是可能具有继承限制的语言构造。我只是在子类中重新实现该方法(见下文)。public [Object] getInstance()
而且,是的,单例也可以从继承中受益,因为它们可能与其他单例共享相似但不识别的行为。
public class ParentSingleton {
private static ParentSingleton instance;
protected ParentSingleton() {
}
public static synchronized ParentSingleton getInstance() {
if (instance == null) {
instance = new ParentSingleton();
}
return instance;
}
public int a() {
// (..)
}
}
public class ChildSingleton extends ParentSingleton {
private static ChildSingleton instance;
public static synchronized ParentSingleton getInstance() {
if (instance == null) {
instance = new ChildSingleton();
}
return instance;
}
}
编辑:正如Eyal在下面的评论中指出的那样,超类中的构造函数必须受到保护(而不是私有),否则子类将不可见,代码甚至无法编译。