通过Consumer接口减少大量的if else

54 阅读2分钟

在我们的程序中,可能会存在大量的运用if-else语句,这些if-else会使代码看起来非常的臃肿,而且也失去了代码的简洁性和低耦合性,所以需要对他进行改造。

现在公司里有一种场景,我们会对消息进行消费,根据tag的不同,会进行不同的消息处理,在原本的处理中,因为版本迭代,慢慢增加了许多的if-else,其中这些tag存储在ConsumerTagEnum枚举里面,根据接受的tag和枚举里的code进行equals比较,进行具体处理。

public Boolean consumer(String consumerTag, String body) {
        if (consumerTag == null) {
            log.info("consumer tag is empty.");
            return Boolean.FALSE;
        }
        if (ConsumerTagEnum.EMP.getCode().equals(consumerTag) || ConsumerTagEnum.LW_EMP.getCode().equals(consumerTag)) {
        ........
       
            return Boolean.TRUE;
        } else if (ConsumerTagEnum.DEPT.getCode().equals(consumerTag) || ConsumerTagEnum.LW_DEPT.getCode().equals(consumerTag)) {
           ........
        }
        // 用户详细信息
        ........
        

        log.info("consumer tag is not support.");
        return Boolean.FALSE;
    }

首先新建一个消息处理类,对于各种消息的详细处理都会写到对应的方法体里面,一种tag对应一个方法。code对应消息的tag,body是具体的消息内容。

@Data
@Slf4j
@Component
@NoArgsConstructor
@AllArgsConstructor
public class ConsumerHandler {

    private String code;
    private String body;

    public static void EMP(ConsumerHandler consumerHandler) {
        log.info("method = EMP, code = {}, body = {}",consumerHandler.code, consumerHandler.body);
    }

    public static void DEPT(ConsumerHandler consumerHandler) {
        log.info("method = DEPT, code = {}, body = {}",consumerHandler.code, consumerHandler.body);
    }

    public static void LW_EMP(ConsumerHandler consumerHandler) {
        log.info("method = LW_EMP, code = {}, body = {}",consumerHandler.code, consumerHandler.body);
    }

}

方法有了之后,怎么将tag与方法绑定起来呢,想到的是在ConsumerTagEnum枚举里面,设计一个map,将tag与方法体手动绑定。

同时设计一个方法,通过tag获取对应的方法引用。

@Getter
public enum ConsumerTagEnum {

    EMP("employee", "员工信息同步"),
    DEPT("dept", "部门信息同步"),
    LW_EMP("lw_employee", "劳务-员工信息同步"),


    private String code;
    private String name;
    private static Map<String, Consumer<ConsumerHandler>> map;
    static {
        map = new HashMap<>();
        map.put(EMP.getCode(),ConsumerHandler::EMP);
        map.put(DEPT.getCode(),ConsumerHandler::DEPT);
        map.put(LW_EMP.getCode(),ConsumerHandler::LW_EMP);
    }

    public static Consumer<ConsumerHandler> getConsumer(String code) {
        return map.get(code);
    }

    ConsumerTagEnum(String code, String name) {
        this.code = code;
        this.name = name;
    }
}

之后就是具体的消费过程:

public Boolean test(String consumerTag, String body) {
        Consumer<ConsumerHandler> consumer = ConsumerTagEnum.getConsumer(consumerTag);
        if (consumer == null) {
            log.info("consumer tag is not support.");
            return Boolean.FALSE;
        }
        consumer.accept(new ConsumerHandler(consumerTag, body));
        return Boolean.TRUE;
    }

获取到具体的Consumer,传入接收到的tag与body,进行消费。