I have a base class that has a private static member:
class Base { private static Base m_instance = new Base(); public static Base Instance { get { return m_instance; } } }
And I want to derive multiple classes from this:
class DerivedA : Base {} class DerivedB : Base {} class DerivedC : Base {}
However, at this point calling DerivedA::Instance will return the same exact object as will DerivedB::Instance and DerivedC::Instance. I can solve this by declaring the instance in the derived class, but then every single derived class will need to do that and that just seems like it should be unneccessary. So is there any way to put all this in the base class? Could a design pattern be applied?
There’s one really icky way of doing this:
This works because there’s one static variable per constructed type – e.g.
List<string>is a different type toList<int>and so would have separate static variables.I’ve taken the opportunity of making it an instance of the derived class as well – I don’t know whether that’s what you want or not, but I thought I’d at least make it available for you 🙂
In general though, this is a nasty thing to do. Static variables aren’t really designed for this kind of use – I’ve just abused a feature of generics to get ‘sort of’ the behaviour you asked for.
Also note that
Base<DerivedA>.Instancewill return the same result asDerivedA.Instance– the property/variable don’t ‘know’ that you’re usingDerivedA.Instance. I don’t know whether or not that’s important to you.With the extra non-generic class, you can write:
If you don’t need that, take it out 🙂