抽象产品角色
public abstract class Operation {
/**
* 获取两个数运算后的值
*
* @param numA 第一个数
* @param numB 第二个数
* @return 结果
*/
public abstract double getResult(double numA, double numB);
}
具体产品类,包括加法、减法、乘法、除法四个运算的具体实现
public class Add extends Operation {
@Override
public double getResult(double numA, double numB) {
return numA + numB;
}
}
public class Sub extends Operation {
@Override
public double getResult(double numA, double numB) {
return numA - numB;
}
}
public class Mul extends Operation {
@Override
public double getResult(double numA, double numB) {
return numA * numB;
}
}
public class Div extends Operation {
@Override
public double getResult(double numA, double numB) {
if (numB == 0) {
System.out.println("除数不能为0");
}
return numA / numB;
}
}
工厂类
public class OperationFactory {
public static Operation createOperation(String operate) {
Operation operation = null;
switch (operate) {
case "+":
operation = new Add();
break;
case "-":
operation = new Sub();
break;
case "*":
operation = new Mul();
break;
case "/":
operation = new Div();
break;
}
return operation;
}
}
客户端
class Client {
public static void main(String[] args) {
Operation operation = OperationFactory.createOperation("+");
operation.getResult(1, 1);
}
}