UML类图:
Java版代码:
abstract class Operation { private double numberA; private double numberB; public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } public abstract double GetResult(); } class OperationAdd extends Operation { @Override public double GetResult() { // TODO Auto-generated method stub double result = 0; result = getNumberA() + getNumberB(); return result; } } class OperationSub extends Operation{ @Override public double GetResult() { // TODO Auto-generated method stub double result=0; result=getNumberA()-getNumberB(); return result; } } class OperationMul extends Operation{ @Override public double GetResult() { // TODO Auto-generated method stub double result=0; result=getNumberA()*getNumberB(); return result; } } class operationDiv extends Operation{ @Override public double GetResult() { // TODO Auto-generated method stub double result=0; if(getNumberB()==0){ System.out.println("除数不能为零!"); }else{ result=getNumberA()/getNumberB(); } return result; } } 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; } } public class SimpleFactory{ public static void main(String[] args){ Operation oper; oper =OperationFactory.createOperate("+"); oper.setNumberA(1); oper.setNumberB(2); double result=oper.GetResult(); System.out.println(result); } }
总结:
这里的工厂类OperationFactory不是与具体的运算类相关联,而是与抽象运算类相关联,这样就降低了耦合度,即使要扩展或修改也不需要大范围的修改代码,
增强了代码的可维护性和可扩展性。