使用函数式接口解决大量if-else/switch

280 阅读1分钟

背景

最近看到之前的项目中,有业务需要从消费队列中接收消息,每一条消息都有一个标识来表示是哪类数据。

在接收时,就会有大量的if-else进行判断从而进行不同的逻辑处理。

这样就不可避免的造成写在后面的判断会经过多次判断,并且程序会显得越来越臃肿。

优化

参考servlet的源码进行优化。

函数式接口回顾

在这里插入图片描述

优化前代码

    @Transactional(rollbackFor = Exception.class)
    public void consumerMessage(String dataType, String msgBody) {
        if ("table1".equals(dataType)) {
          //业务代码
        } else if ("table2".equals(dataType)) {
       //业务代码
        } else if ("table3".equals(dataType)) {
         //业务代码
        } 
}

可想而知,如果有大量的业务逻辑需要执行,就要有大量的if-else要进行判断

优化后的代码

@Service
@Slf4j
public class ConsumerService {

    private final Map<String, Consumer<String>> consumerMap = new HashMap<>();

	//默认初始化方法
    @PostConstruct
    private void dispatcherTask() {
        consumerMap.put("table1", (msgBody) -> this.saveXXXTable1(msgBody));
        consumerMap.put("table2", (msgBody) -> this.saveXXXTable2(msgBody));
    }
	
	//提供外部调用方法
    public void executeConsumer(String dataType, String msgBody) {
        Consumer<String> consumer = consumerMap.get(dataType);
        if (null != consumer) {
            consumer.accept(msgBody);
        }
    }

    private void saveXXXTable1(String msgBody) {
      //业务代码
    }

    private void saveXXXTable2(String msgBody) {
      //业务代码
    }
}


自此就顺利的将旧代码进行改造。后续会继续学习尝试使用设计模式来进行优化。