Function函数实现去除多个if

发布时间 2023-06-02 16:12:24作者: Husir_Boky

声明接口:

/**
* 任务函数
* taskPush()、taskCheckStatus()、fileData()实现业务的方法
* @return
*/
public Map<String, Consumer<Entity>> taskConsumer() {
    Map<String, Consumer<Entity>> t = new HashMap<>(Constant.MAPINITSIZE);
t.put(Constant.TASKPUSH, m -> taskPush(m));
t.put(Constant.TASKCHECKSTATUS, m -> taskCheckStatus(m));
t.put(Constant.FILEDATA, m -> fileData(m));
return t;
}
使用:
public void consumerMqMessage(Entity entity) {
Optional.ofNullable(entity.getMsgType()).ifPresent(msg -> {
     // 决定调用那个业务方法
String msgType = ActiveMqManager.base64CodeToStr(msg.getData());
Map<String, Consumer<Entity>> consumerMap = mqManager.taskConsumer();
Optional.ofNullable(consumerMap.get(msgType)).ifPresent(task -> task.accept(entity.getDataMsgs()));
});
}