62,047
社区成员
发帖
与我相关
我的任务
分享
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//ConsoleApplication1.ManFactory可以写到配置文件中,此处略
IFactory carFactory = CarFactory.CreateFacory("ConsoleApplication1.ManFactory");
IHuman hyman = carFactory.GetMarried();
hyman.Run();
Console.ReadKey();
}
public class CarFactory
{
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;
}
}
public interface IFactory
{
IHuman GetMarried();
}
}
public interface IHuman
{
void 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");
}
}
public class WomanFactory : Program.IFactory
{
public IHuman GetMarried()
{
return new Woman();
}
}
public class ManFactory : Program.IFactory
{
public IHuman GetMarried()
{
return new Man();
}
}
}
public interface IFactory
{
IHuman GetMarried();
}