20230418 1. 简单工厂模式 - 计算器

发布时间 2023-06-19 09:46:21作者: 流星<。)#)))≦

简单工厂模式实现计算器

简单工厂模式

定义运算类

public abstract class Operation {
    public abstract double getResult(double a, double b);
}

运算类的几个实现子类,可随业务灵活修改和扩充

public class Add extends Operation {
    @Override
    public double getResult(double a, double b) {
        return a + b;
    }
}

public class Div extends Operation {
    @Override
    public double getResult(double a, double b) {
        if (b == 0) {
            throw new ArithmeticException("除数不能为0");
        }
        return a / b;
    }
}

简单工厂类

public class OperationFactory {
    public static Operation createOperation(String oper) {
        Operation operation = null;
        switch (oper) {
            case "+": {
                operation = new Add();
                break;
            }
            case "/": {
                operation = new Div();
                break;
            }
        }
        return operation;
    }
}

客户端类

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double a = scanner.nextDouble();
        String oper = scanner.next();
        double b = scanner.nextDouble();

        Operation operation = OperationFactory.createOperation(oper);
        System.out.println(operation.getResult(a, b));
    }
}