首页 > 代码库 > 设计模式之简单工厂模式
设计模式之简单工厂模式
UML图
namespace Study2014.CjModelDesign { /// <summary> /// 2014-5-19 /// 简单封装 /// 过程式开发? /// </summary> public class Operation { public static double GetOldResult(double numberA, double numberB, string operate) { double result = 0; switch (operate) { case "+": result = numberA + numberB; break; case "-": result = numberA - numberB; break; case "*": result = numberA * numberB; break; case "/": if (numberB == 0) { throw new Exception("被除数不能为0"); } result = numberA / numberB; break; } return result; } //另一种写法 public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() { return 0; } } }
namespace Study2014.CjModelDesign { /// <summary> /// +操作 简单工厂 /// </summary> public class OperationAdd:Operation { public override double GetResult() { return this.NumberA + this.NumberB; } } }
namespace Study2014.CjModelDesign { /// <summary> /// 除 操作 简单工厂 /// </summary> public class OperationDiv:Operation { public override double GetResult() { if (this.NumberB == 0) { throw new Exception("除数不能为0"); } return this.NumberA / this.NumberB; } } }
public class OperationFactory { /// <summary> /// 简单工厂模式 /// /// </summary> /// <param name="operate"></param> /// <returns></returns> public static Operation CreateOperation(string operate) { //多态 Operation op = null; switch (operate) { case "+": op = new OperationAdd(); break; case "-": op = new OperationSub(); break; case "*": op = new OperationMul(); break; case "/": op = new OperationDiv(); break; } return op; } }
总结一下这样写的好处
- 松耦合,后续增加其他的业务类(如:平方等),只需增加一个新的子类(从Operation继承),再修改工厂的代码(加个分支).
- 其他的没想到...
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。