具体实现如下:
Operation:
public abstract class Operation {
abstract double getResult(double a, double b) throws Exception;
}
AddOperation:
public class AddOperation extends Operation {
@Override
double getResult(double a, double b) {
return a + b;
}
}
MulOperation:
public class MulOperation extends Operation {
@Override
double getResult(double a, double b) {
return a * b;
}
}
SubOperation:
public class SubOperation extends Operation {
@Override
double getResult(double a, double b) {
return a - b;
}
}
DivOperation:
public class DivOperation extends Operation {
@Override
double getResult(double a, double b) throws Exception {
if (b == 0) {
throw new Exception("除数不能为0");
} else {
return a/b;
}
}
}
OperationFactory:
public class OperationFactory {
public static Operation getOperation(String operation) {
Operation oper = null;
switch (operation) {
case "+":
oper = new AddOperation();
break;
case "-":
oper = new SubOperation();
break;
case "*":
oper = new MulOperation();
break;
case "/":
oper = new DivOperation();
break;
}
return oper;
}
}
测试类Calculator:
public class Calculator {
public static void main(String args[]) {
double a = 1.0;
double b = 2.0;
Operation oper = OperationFactory.getOperation("+");
try {
double result = oper.getResult(a,b);
System.out.print("结果是:" + result);
} catch (Exception e) {
System.out.print("除数不能为0");
}
}
}
运行结果:
结果是:3.0
Process finished with exit code 0