控制台程序示例:
单例的设计:
class Manager
{
private static Manager _instance = null;
public static Manager CreateInstance()
{
if (_instance == null)
{
_instance = new Manager();
}
return _instance;
}
private Manager()
{
}
Dictionary<string, BaseModel> dic = new Dictionary<string, BaseModel>();
public void ResisterModel(string modelName,BaseModel bm)
{
if (!dic.ContainsKey(modelName))
{
dic.Add(modelName,bm);
}
}
public BaseModel GetModel(string modelName)
{
if(dic.ContainsKey(modelName))
{
return dic[modelName];
}
return null;
}
public void RemoveModel(string modelName)
{
if(dic.ContainsKey(modelName))
{
dic.Remove(modelName);
}
}
}
}
调用地方的设计:
class Program
{
static void Main(string[] args)
{
Manager mm = Manager.CreateInstance();
mm.ResisterModel(model1.name,new model1());
mm.ResisterModel(model2.name,new model2());
model1 m1 = mm.GetModel(model1.name) as model1;
model2 m2 = mm.GetModel(model2.name) as model2;
Console.WriteLine(m1.GetName());
Console.WriteLine(m2.GetName());
Console.ReadKey();
}
}
此外,例子中使用的model和basemodel,
class BaseModel
{
public string name = string.Empty;
}
class model1:BaseModel
{
public static new string name = "model1";
public string GetName()
{
int a = 11;
return a.ToString();
}
}
class model2:BaseModel
{
public static new string name = "22";
public string GetName()
{
return name;
}
}