抽象工廠,大名鼎鼎的設計模式之一,我這僅做了一個例子,來簡單記錄一下,先來類圖
具體代碼
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
}
}