涉及静态成员的事实使我想,一种基于独裁的方法是最佳的,除非你想援引思考,并列举复国的方法。 这是一部行之有效的样本代码。
// 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);
}
每个儿童班级都安装固定构造器,以在我的榜样中创建单一县,这种做法过于简单化,但我相信,你有更好的办法这样做:
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();
}
}
管理人员将采用这种方式:
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();
}
}
青春期产出:
XManager Instance: index was 2
YManager Instance: index was 4
Press enter to exit
我确信,这样做的方法比较棘手,但我只想说明如何建立和接触独裁者,以支持单一州。