01 简单工厂模式

简单工厂模式

1. 接口

//计算器基类
public interface Operation {

    /**
     * 获取计算结果
     *
     * @param numberA numberA
     * @param numberB numberB
     * @return result
     */
    double getResult(double numberA, double numberB);
}

2. 实现类

//加法
public class AddOperation implements Operation {

    @Override
    public double getResult(double numberA, double numberB) {
        return numberA + numberB;
    }
}

//减法
public class SubOperation implements Operation {
    @Override
    public double getResult(double numberA, double numberB) {
        return numberA - numberB;
    }
}

//乘法
public class DivOperation implements Operation {
    @Override
    public double getResult(double numberA, double numberB) {
        return numberA * numberB;
    }
}

//除法
public class MulOperation implements Operation {
    @Override
    public double getResult(double numberA, double numberB) {
        if (numberB == 0) {
            throw new ArithmeticException("除数不能为零");
        }
        return numberA / numberB;
    }
}

3. 工厂类

//计算器工厂
public class OperationFactory {

    /**
     * 获取具体计算器
     *
     * @param operate 计算类型
     * @return 计算器
     */
    public static Operation createOperate(String operate) {
        Operation operation = null;
        switch (operate) {
            case "+":
                operation = new AddOperation();
                break;
            case "-":
                operation = new SubOperation();
                break;
            case "*":
                operation = new DivOperation();
                break;
            case "/":
                operation = new MulOperation();
                break;
        }
        return operation;
    }
}

4. 运行结果

@Slf4j
public class Client {
    public static void main(String[] args) {
        try {
            OperationService operate = OperationFactory.createOperate("/");
            if (Objects.isNull(operate)) {
                log.info("没有此计算器");
            }
            double result = operate.getResult(5.1, 0);
            log.info("计算结果: {}", result);
        } catch (Exception e) {
            log.error("计算异常, msg:{}", e.getMessage(), e);
        }
    }
}
posted @ 2020-12-02 22:02  芝諾de乌龟  阅读(47)  评论(0编辑  收藏  举报