我该如何从单例类继承到其他需要相同功能的类中呢?是否可以采用这种方式实现?
Jon Skeet曾经写过这方面的内容,可以参考这里。虽然使用嵌套内部类不是很理想,但通过Singleton可以实现继承的一些好处。它并没有无限的可扩展性,只是一种让Singleton在运行时选择自己的实现技术。
实际上,从Singleton进行继承并没有太多意义,因为Singleton模式的一部分是实例管理。一旦你已经拥有了一个基类型的实例,就太晚了去在派生类型中覆盖它的任何部分。即使你可以这样做,我认为它可能会导致设计难以理解,也更加难以测试和维护。
public abstract class Animal {
protected static Animal instance;
public static Animal theInstance(){
assert instance != null : "Cannot instantiate an abstract Animal";
return instance;
}
abstract void speak();
}
public class Dog extends Animal{
protected Dog(){}
public static Animal theInstance(){
if (instance == null){
instance = new Dog();
}
return instance;
}
@Override
void speak() {
System.out.println("Wouf");
}
}
Dog.theInstance()
,任何后续客户端都会调用Animal.theInstance()
。这样,客户端可以完全独立于派生类,并且可以添加新的子类而无需重新编译客户端(开闭原则)。有人可以随便纠正我,但是我理解的方式,并且曾经因此出现过错误:
public class BaseClass
{
protected static List<string> ListOfSomething { get; set; }
}
public class ChildClass
{
protected static List<int> ListOfSomethingElse { get; set; }
}
public class AnotherChildClass
{
protected static List<int> ListOfSomethingElse { get; set; }
}
这两个子类会共享同一个ListOfSomething
,它们不会拥有自己的副本。相同的静态对象将在所有子类中共享。 这是单例行为和继承的蜕变。正如Silky所说...你只是不应该这样做,否则你可能会遇到类似的问题。
如果你不是在谈论这种情况...我不确定你在谈论什么单例模式,举个例子会很有帮助,因为单例有很多特定用途。