1.定义一个接口:人类,它可以有跑这样的一个动作(估且这么说吧)
public interface IHuman
{
void Run();
}
2.来一个男人和一个女人,让他们继承人类,当然了,要去实现Run()方法
public class Woman : IHuman
{
public Woman()
{
Console.WriteLine("The girl fall in love");
}
public void Run()
{
Console.WriteLine("There is a girl in the running");
}
}
public class Man : IHuman
{
public Man()
{
Console.WriteLine("The guy fall in love");
}
public void Run()
{
Console.WriteLine("A guy with the girl behind");
}
}
3.下面我们来搭建加工厂模板
public interface IFactory
{
/// <summary>
/// 声明一个 GetMarried 返回 IHuman 实例
/// </summary>
/// <returns>返回 IHuman 实例</returns>
IHuman GetMarried();
}
public class WomanFactory : IFactory
{
public IHuman GetMarried()
{
return new Woman();
}
}
public class ManFactory : IFactory
{
public IHuman GetMarried()
{
return new Man();
}
}
4.写一个方法用来生成对应的加工厂
public class HumanFactory
{
public static IFactory CreateFacory(string factoryType)
{
Type t = Type.GetType(factoryType);
return Activator.CreateInstance(t) as IFactory;
//另一种方法创建实体工厂对象Assembly.Load(程序集名称).CreateInstance(命名空间.类名)
//IFactory carFactory = System.Reflection.Assembly.Load("ConsoleApplication1").CreateInstance(factoryType) as IFactory;
//return carFactory;
}
}
5.测试一下:
class Program
{
static void Main(string[] args)
{
#region demo1
//ConsoleApplication1.ManFactory可以写到配置文件中,此处略
IFactory humFactory = HumanFactory.CreateFacory("ConsoleApplication1.ManFactory");
IHuman hyman = humFactory.GetMarried();
hyman.Run();
Console.ReadKey();
#endregion
}
}
效果: