if/else问题解决(二)策略模式+工厂方法消除

过去的,未来的
2020-03-25 / 0 评论 / 0 点赞 / 674 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-03-25,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

一、案例

假设需求为,根据类型,处理相对应的操作,优化前有以下代码:

  public void operation(String type){
        if("add".equals(type)){
            //执行加法
        }else if("sub".equals(type)){
            //执行减法
        }
        //这里还有很多操作
    }

二、方案

1、定义接口
public interface OperationService {
    Integer operation(Integer num1, Integer num2);

    String getType();
}
2、实现各个逻辑策略实现类
public class AddOperationImpl implements OperationService {

    @Override
    public Integer operation(Integer num1, Integer num2) {
        return num1 + num2;
    }

    @Override
    public String getType() {
        return "add";
    }
}
public class SubOperationImpl implements OperationService {

    @Override
    public Integer operation(Integer num1, Integer num2) {
        return num1 - num2;
    }

    @Override
    public String getType() {
        return "sub";
    }
}
3、编写策略工厂类

public class OperationServicesFactory {

    private static final Map<String, OperationService> map = new HashMap<>();
    static {
        map.put("add", new AddOperationImpl());
        map.put("sub", new SubOperationImpl());
    }

    public static OperationService getOperationService(String type) {
        return map.get(type);
    }

}
4、最终测试
   public static void main(String[] args) {
        String type="add";
        OperationService operation = OperationServicesFactory.getOperationService("type");
        System.out.println(operation.operation(1, 2));
    }
    
0

评论区