Operation运算类
class Operation { private double _numberA = 0; public double NumberA { get { return _numberA; } set { _numberA = value; } } private double _numberB = 0; public double NumberB { get { return _numberB; } set { _numberB = value; } } public virtual double GetResult() { double result = 0; return result; } }
加减乘除类
class OperationAdd : Operation { public override double GetResult() { return NumberA + NumberB; } } class OperationSub : Operation { public override double GetResult() { return NumberA - NumberB; } } class OperationMul : Operation { public override double GetResult() { return NumberA * NumberB; } } class OperationDiv : Operation { public override double GetResult() { if (NumberB == 0) throw new Exception("除数不能为0"); return NumberA / NumberB; } }
工厂类
class OperationFactory { public static Operation CreateOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } }
客户端代码
Operation oper = OperationFactory.CreateOperate("/"); oper.NumberA = 1; oper.NumberB = 0; double result = oper.GetResult();
总结:
简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。但此模式违背了开放-封闭原则。