问题
How do I inherit from a singleton class into other classes that need the same functionality? Would something like this make any sense?
回答1:
Jon Skeet wrote about this a while back. It is possible to achieve some of the benefits of inheritance with the Singleton, although using nested inner classes does leave a little to be desired. It doesn't have infinite extensibility, it's only a technique for having a Singleton choose its own implementation at runtime.
Realistically, inheriting from a Singleton doesn't make all that much sense, because part of the Singleton pattern is instance management, and once you already have a physical instance of a base type then it's too late to override any of this in the derived type. Even if you could, I suspect that it could lead to a design that's difficult to understand and even more difficult to test/maintain.
回答2:
You can inherit from singleton and for "reuse" or some fine tuning using templates (C++) or generics (C#.NET).
I've posted in my blog (www.devartplus.com) a serie of posts in this subject:
1) Basic singleton inheritance in C#.NET
2) Thread-safe singleton inheritance in C#.NET
3) Several singleton implementations in C++
You are invited to visit those links, and share with all your opinion. Good luck.
回答3:
Someone feel free to correct me, but the way I understand it, and had an error with this once:
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; }
}
Both of the child classes would share the same ListOfSomething
, they would not have their own copy. The same static one would be shared amongst all children. This is the molt of singleton behavior and inheritance. As silky said...you just shouldn't do it, you'll probably run into something along these lines.
If you're not talking about something like this...I'm not sure what singleton you're speaking of, and an example would help greatly, since singleton's have a great deal of niche uses.
来源:https://stackoverflow.com/questions/2166430/singleton-inheritance