We have the following class hierarchy:
public interface IManager {
object GetObject(int);
}
public class BaseManager : IManager ...
public class XManager : BaseManager {
...
public static XManager Instance;
}
public class YManager : BaseManager {
...
public static YManager Instance;
}
public static class ManagerFacade {
private static IManager GetManager(type);
public static object GetObject(type, int) {
return GetManager(type).GetObject(int); }
}
How would you implement the GetManager() function?
Is it possible to collect these types and their instances (or instance creating delegates) in a static dictionary in the static constructors of these classes?
(Thank you Jon, I only remembered “something is different in .Net 4”, but not the details)
Other ways would use class attributes or descendents of BaseManager or looking for implementations of IManager.
What is the preferred solution?
The fact that static members are involved makes me think that a dictionary-based approach is the best, unless you want to invoke reflection and figure out the method for retrieving the singleton. This is a working sample code I was able to come up with:
The child classes each implement a static constructor to create the singleton instance in my example, which is way too simplistic, but I’m sure you have a better way to do this:
The ManagerFacade would implement the dictionary this way:
The console app to test out the manager facade:
Console output:
I’m sure that there’s more elegant ways to do this, but I just wanted to illustrate how to set up and access the dictionary to support the singletons.