工厂方法模式
定义:把具体产品的创建推迟到子类中,工厂类不再负责所有产品的创建,而只是给出具体工厂必须实现的接口,由产品工厂类来继承实现。
优点:工厂方法模式通过面向对象编程中的多态性来将对象的创建延迟到具体工厂中,从而解决了简单工厂模式中存在的问题,也很好地符合
了开放封闭原则(即对扩展开发,对修改封闭)。
关键点:一个抽象产品基类、一个抽象工厂基类、多个产品子类、多个产品工厂子类。
适用场景:可适用于大部分业务需求。
示例:
#region 抽象基类 /// <summary> /// 抽象产品基类 /// </summary> public abstract class TransportationEx { public abstract string TransportMethod(); } /// <summary> /// 抽象工厂基类 /// </summary> public abstract class FactoryCreator { public abstract TransportationEx GetTransportMethod(); } #endregion #region 产品子类 /// <summary> /// 地铁 /// </summary> public class ByMetroEx:TransportationEx { public override string TransportMethod() { return "座地铁"; } } /// <summary> /// OFO /// </summary> public class ByOfoEx:TransportationEx { public override string TransportMethod() { return "骑OFO"; } } /// <summary> /// 走路 /// </summary> public class OnFootEx:TransportationEx { public override string TransportMethod() { return "开11号"; } } #endregion #region 产品工厂类 /// <summary> /// 地铁工厂类 /// </summary> public class MetroFactory:FactoryCreator { public override TransportationEx GetTransportMethod() { return new ByMetroEx(); } } /// <summary> /// OFO工厂类 /// </summary> public class OfoFactory:FactoryCreator { public override TransportationEx GetTransportMethod() { return new ByOfoEx(); } } /// <summary> /// 走路工厂类 /// </summary> public class OnFootFactory:FactoryCreator { public override TransportationEx GetTransportMethod() { return new OnFootEx(); } } #endregion
调用
#region 工厂方法模式 Console.WriteLine("【工厂方法模式】"); Console.WriteLine(); Console.WriteLine("出行方式:"); Console.WriteLine(); FactoryCreator fc1 = new MetroFactory(); Console.WriteLine(fc1.GetTransportMethod().TransportMethod()); Console.WriteLine(); FactoryCreator fc2 = new OfoFactory(); Console.WriteLine(fc2.GetTransportMethod().TransportMethod()); Console.WriteLine(); FactoryCreator fc3 = new OnFootFactory(); Console.WriteLine(fc3.GetTransportMethod().TransportMethod()); Console.WriteLine(); Console.ReadLine(); #endregion
输出:
くろさきいちご