简单工厂模式——学习《大话设计模式》
最近一段时间在学习《大话设计模式》,我觉得这本真的很不错,以下是我学习第一章 简单工厂模式后整理的代码,请大家多指导,小弟刚出炉。
//运算类 public class Operation { private double _numberA=0; private double _numberB=0; public double NumberA { set { _numberA=value; } get { return _numberA; } } public double NumberB { set { _numberB=value; } get { return _numberB; } } public virtual double GetResult() { double result=0; return result; } } //加法运算子类 public class OperationAdd:Operation { public override double GetResult() { double result=0; result=NumberA+NumberB; return result; } } //减法运算子类 public class OperationSub:Opertion { public override double GetResult() { double result=0; result=NumberA-NumberB; return result; } } //乘法运算子类 public class OperationMul:Operation { public override double GetResult() { double result=0; result=NuberA*NumberB; return result; } } //除法运算子类 public class OperationDiv:Operation { public override double GetResult() { double result=0; if(NumberB==0) throw new Exception("除数不能为零"); result=NumberA/NumberB; return result; } } //简单工厂类 public class OperationFactory { public static Operation createOperate(string operate) { Operration oper=null; swith(operate) { case "+": oper=new OperationAdd(); break; case "-": oper=new OperationSub(); break; case "*": oper=new OperationMul(); break; case "/": oper=new OperationDiv(); break; } return oper; } } //客户端调用代码 public class Client { public static void Main(string[] args) { Operation oper; oper=OperationFactory.createOperate("+"); oper.NumberA=1; oper.NumberB=2; double result=oper.GetResult(); } }