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:
// Added another interface - GetInstance
public interface IManager
{
object GetObject(int i);
}
// made BaseManager abstract; you don't have to do that, but then
// remember to make everything virtual, etc etc.
public abstract class BaseManager : IManager
{
public abstract object GetObject(int i);
}
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:
public class XManager : BaseManager
{
public static XManager Instance;
static XManager() { Instance = new XManager(); }
public override object GetObject(int i)
{
return "XManager Instance: index was " + i.ToString();
}
}
public class YManager : BaseManager
{
public static YManager Instance;
static XManager() { Instance = new YManager(); }
public override object GetObject(int i)
{
return "YManager Instance: index was " + i.ToString();
}
}
The ManagerFacade would implement the dictionary this way:
public static class ManagerFacade
{
private static readonly Dictionary<Type, IManager> managerInstances
= new Dictionary<Type, IManager>()
{
{typeof(XManager), XManager.Instance},
{typeof(YManager), YManager.Instance}
};
private static IManager GetManager<T>() where T: IManager
{
return managerInstances[typeof(T)];
}
public static object GetObject<T>(int i) where T: IManager
{
return GetManager<T>().GetObject(i);
}
}
The console app to test out the manager facade:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ManagerFacade.GetObject<XManager>(2).ToString());
Console.WriteLine(ManagerFacade.GetObject<YManager>(4).ToString());
// pause program execution to review results...
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
Console output:
XManager Instance: index was 2
YManager Instance: index was 4
Press enter to exit
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.