if-else的另一种实现

2019-09-24  本文已影响0人  OPice

背景

在日常开发中,经常会需要监听某种数据的新增、删除、修改。根据不同类型做处理,通常处理:

public interface MqService {
    /**
     * 处理mq消息
     *
     * @param mqMessageDTO
     * @return
     */
    Boolean handlerMsg(MQMessageDTO mqMessageDTO);
}

@Service
@Slf4j
public class MqServiceImpl implements MqService {
    @Override
    public Boolean handlerMsg(MQMessageDTO mqMessageDTO) {
        try {
            if (MQMessageDTO.MsgType.INSERT == mqMessageDTO.getMsgType()) {
               // 处理新增数据
            } else if (MQMessageDTO.MsgType.UPDATE == mqMessageDTO.getMsgType()) {
               //处理修改数据
            } else if (MQMessageDTO.MsgType.DELETE == mqMessageDTO.getMsgType()) {
               //处理删除数据
            }
            return true;
        } catch (Exception e) {
            log.error("消息消费失败:{}", mqMessageDTO);
            e.printStackTrace();
            return false;
        }
    }
}

这样如果类型较多会有大量if-else分支逻辑,我们可以换一种模式实现

定义三个不同类型的Handler

@Component
@HandlerAnnotation(MQMessageDTO.MsgType.DELETE)
public class DeleteHandler extends AbstractHandler {
    @Override
    public void handler() {
        System.out.println("收到删除消息");
    }
}
@Component
@HandlerAnnotation(MQMessageDTO.MsgType.INSERT)
public class InsertHandler extends AbstractHandler {
    @Override
    public void handler() {
        System.out.println("收到新增消息");
    }
}
@Component
@HandlerAnnotation(MQMessageDTO.MsgType.UPDATE)
public class UpdateHandler extends AbstractHandler {
    @Override
    public void handler() {
        System.out.println("收到更新消息");
    }
}

定义一个注解,根据注解来调用哪个handler处理

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface HandlerAnnotation {
    MQMessageDTO.MsgType value();
}

工厂初始化的时候,注册HandlerContext

@Data
public class HandlerContext {
    private Map<String, Object> handlerMap;

    public HandlerContext(Map<String, Object> handlerMap) {
        this.handlerMap = handlerMap;
    }
}


@Component
public class HandlerProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<String, Object> beansWithAnnotation = configurableListableBeanFactory.getBeansWithAnnotation(HandlerAnnotation.class);
        Map<String, Object> typeHandler = Maps.newHashMap();
        beansWithAnnotation.keySet().forEach(beanName -> {
            MQMessageDTO.MsgType value = beansWithAnnotation.get(beanName).getClass().getAnnotation(HandlerAnnotation.class).value();
            typeHandler.put(value.name(),beansWithAnnotation.get(beanName));
        });
        HandlerContext handlerContext = new HandlerContext(typeHandler);
        configurableListableBeanFactory.registerResolvableDependency(HandlerContext.class, handlerContext);
    }
}

替换过的实现

@Service
@Slf4j
public class MqServiceImpl implements MqService {
    @Autowired
    private HandlerContext handlerContext;

    @Override
    public Boolean handlerMsg(MQMessageDTO mqMessageDTO) {
        try {
            /*if (MQMessageDTO.MsgType.INSERT == mqMessageDTO.getMsgType()) {
               // 处理新增数据
            } else if (MQMessageDTO.MsgType.UPDATE == mqMessageDTO.getMsgType()) {
               //处理修改数据
            } else if (MQMessageDTO.MsgType.DELETE == mqMessageDTO.getMsgType()) {
               //处理删除数据
            }*/
            Map<String, Object> handlerMap = handlerContext.getHandlerMap();
            AbstractHandler handler = (AbstractHandler)handlerMap.get(mqMessageDTO.getMsgType().name());
            handler.handler();
            return true;
        } catch (Exception e) {
            log.error("消息消费失败:{}", mqMessageDTO);
            e.printStackTrace();
            return false;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读