大话设计模式之简单工厂模式
面向对象:封装、继承、多态,使得程序的耦合度降低,代码可以复用。
业务的封装:让业务逻辑与界面逻辑分开,耦合度降低。
简单的计算器程序
1)封装和继承
//定义一个Operation类 public class Operation { //操作数 private double NumberA {get;set;} private double NumberB {get;set;} private 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:Operation { public override double GetResult() { double result =0; result = NumberA - NumberB; return result; } } public class OperationMul:Operation { public override double GetResult() { double result =0; result = NumberA * NumberB; return result; } } public class OperationDiv:Operation { public override double GetResult() { double result =0; if(NumberB == 0) throw new Exception("除数不能为0"); result = NumberA / NumberB; return result; } }
2)简单工厂类
public class OperationFactory { public static Operation CreateOperation(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 =null; oper = OperationFactory.CreateOperation("+"); oper.NumberA=10; oper.NumberB=15; double result = oper.GetResult();
3)UML类图图示样例