c# 设计模式 之:工厂模式之---工厂模式
1、uml类图:
实现和依赖关系:
实现:
SportFactory、JeepFactory、HatchbackFactory 实现 IFactory 接口
SportCar、JeepCar、HatchbackCar 实现 ICar 接口
依赖:
IFactory 依赖 ICar
SportFactory 依赖 SportCar
JeepFactory 依赖 JeepCar
HatchbackFactory 依赖 HatchbackCar
Client依赖 IFactory 和 ICar
2、代码实现:
抽象工厂代码:
namespace CNBlogs.DesignPattern.Common { public interface IFactory { ICar CreateCar(); } }
抽象产品代码:
namespace CNBlogs.DesignPattern.Common { public interface ICar { void GetCar(); } }
具体工厂代码:
namespace CNBlogs.DesignPattern.Common { /// <summary> /// 具体工厂类: 用于创建跑车类 /// </summary> public class SportFactory : IFactory { public ICar CreateCar() { return new SportCar(); } } /// <summary> /// 具体工厂类: 用于创建越野车类 /// </summary> public class JeepFactory : IFactory { public ICar CreateCar() { return new JeepCar(); } } /// <summary> /// 具体工厂类: 用于创建两厢车类 /// </summary> public class HatchbackFactory : IFactory { public ICar CreateCar() { return new HatchbackCar(); } } }
具体产品代码:
namespace CNBlogs.DesignPattern.Common { /// <summary> /// 具体产品类: 跑车 /// </summary> public class SportCar : ICar { public void GetCar() { Console.WriteLine("场务把跑车交给范·迪塞尔"); } } /// <summary> /// 具体产品类: 越野车 /// </summary> public class JeepCar : ICar { public void GetCar() { Console.WriteLine("场务把越野车交给范·迪塞尔"); } } /// <summary> /// 具体产品类: 两箱车 /// </summary> public class HatchbackCar : ICar { public void GetCar() { Console.WriteLine("场务把两箱车交给范·迪塞尔"); } } }
客户端代码:
static void Main(string[] args) { // 工厂类的类名写在配置文件中可以方便以后修改 string factoryType = ConfigurationManager.AppSettings["FactoryType"]; // 利用.NET提供的反射可以根据类名来创建它的实例,非常方便 var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly(); IFactory factory = Assembly.LoadFrom(currentAssembly.CodeBase).CreateInstance(factoryType) as IFactory; ICar car = factory.CreateCar(); car.GetCar(); Console.ReadKey(); }
App.config:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="FactoryType" value="CAFactory.HatchbackFactory"/> </appSettings> </configuration>