C#结合反射实现抽象工厂
时间:2011-04-04 来源:杨延成
抽象工厂,大名鼎鼎的设计模式之一,我这仅做了一个例子,来简单记录一下,先来类图
具体代码
namespace AbstractFactoryTest
{
class Program
{
static void Main(string[] args)
{
//具体工厂类型可以由配置文件中读取
IFactory carFactory = CarFactory.CreateFacory("ThreadTest.AudiFactory");
ICar car = carFactory.CreateCar();
car.Run();
}
}
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 = Assembly.Load("ConsoleApplication2").CreateInstance(factoryType) as IFactory;
//return carFactory;
}
}
public interface IFactory
{
ICar CreateCar();
}
public class AudiFactory : IFactory
{
#region IFactory 成员
public ICar CreateCar()
{
return new AudiCar();
}
#endregion
}
public class DasAutoFactory : IFactory
{
#region IFactory 成员
public ICar CreateCar()
{
return new DasautoCar();
}
#endregion
}
public interface ICar
{
void Run();
}
public class AudiCar : ICar
{
#region ICar 成员
public void Run()
{
Console.WriteLine("Audi.........");
}
#endregion
}
public class DasautoCar : ICar
{
#region ICar 成员
public void Run()
{
Console.WriteLine("Dasauto.............");
}
#endregion
}
}
相关阅读 更多 +