大话设计-工厂模式
记录大话设计学习过程。
“工厂模式”和“简单工厂模式”的区别就是把“到底实例哪一个对象的判断逻辑”迁移出去。因为,如果是简单工厂,哪天增加了新的运算,就必须修改简单工厂类的判断分支,这违反了“开放-封闭原则”。
现在判断逻辑依然有,只是放在了客户端,如果哪天增加新的运算,如果使用工厂模式,扩展就通过增加工厂和运算类,而判断逻辑只需修改客户端。
using System; namespace ConsoleApp4 { class Program { public static void Main(string[] args) {
// if(+)addFactory,if(sub) subFactory 判断省略 var operationFactory = new AddFactory(); var operation = operationFactory.CreateOperation(); operation.NumberA = Convert.ToDouble(Console.ReadLine()); operation.NumberB = Convert.ToDouble(Console.ReadLine()); Console.WriteLine(operation.GetResult()); Console.ReadLine(); } } interface IFactory { Operation CreateOperation(); } // 一个工厂,一个实例 class AddFactory : IFactory { public Operation CreateOperation() { return new OperationAdd(); } } class SubFactory : IFactory { public Operation CreateOperation() { return new OperationSub(); } } //运算基类 public class Operation { private double numberA; public double NumberA { get { return numberA; } set { numberA = value; } } private double numberB; public double NumberB { get { return numberB; } set { numberB = value; } } public virtual double GetResult() { double result = 0; return result; } } public class OperationAdd : Operation { public override double GetResult() { return NumberA + NumberB; } } public class OperationSub : Operation { public override double GetResult() { return NumberA - NumberB; } } }
工厂模式
量变会引起质变。