如果说数学是思维的体操,那设计模式就是面向对象编程思维的体操;
简易计算器类结构图:
操作类,定义两个操作数,并声明抽象方法getResult(),具体实现由子类完成;
public abstract class Operation {
private double numberA;
private double numberB;
public abstract double getResult() throws Exception;
}
加法操作类,实现抽象方法;
public class OperationAdd extends Operation {
@Override
public double getResult() {
return getNumberA() + getNumberB();
}
}
public class OperationDiv extends Operation {
@Override
public double getResult() throws Exception {
if(getNumberB() == 0) {
throw new Exception("被除数不能为0!");
}
return getNumberA() / getNumberB();
}
}
生成操作对象的工厂类:
public class OperationFactory {
public static Operation createOperation(String operate) throws Exception {
Operation operation = null;
switch(operate.trim()) {
case "+":
operation = new OperationAdd();
break;
case "-" :
operation = new OperationSub();
break;
case "*" :
operation = new OperationMul();
break;
case "/" :
operation = new OperationDiv();
break;
default:
throw new Exception("输入的运算符号有误!");
}
return operation;
}
}
客户端代码:
public class OperationMain {
public static void main(String[] args) throws Exception {
Operation operation = OperationFactory.createOperation("*");
operation.setNumberA(15);
operation.setNumberB(18);
System.out.println(operation.getResult());
}
}
如果再增加其他运算方法如开方,新建开方操作类,继承操作类,并实现抽象方法,并且在工厂类的switch-case中增加分支即可!