应用场景

通常在我们需要new多个对象的时候,需要写很多个if else分支,根据不同场景来创建对象;我们可以通过初始化方式,批量创建对象。通常有如下3种形式:

先看一个具体场景例子,我们需要根据不同topic创建具体topic的实现子类,不想写几十个if/else;

方式一clazz.newInstance

  1. DISPATCH_INFO(RetryBizEnum.DISPATCH_INFO.getValue(), FullBizCodeEnum.D1003, OrderSyncDispatchInfoConsumer.TOPIC, OrderSyncDispatchInfoConsumer.class);
  2. /**
  3. * 处理类bean
  4. */
  5. private final Class<AbstractConsumerBase> dealBean;
  6. ConsumerEnum(int bizType, FullBizCodeEnum bizCode, String topic, Class dealBean) {
  7. this.bizType = bizType;
  8. this.bizCode = bizCode;
  9. this.topic = topic;
  10. this.dealBean = (Class<AbstractConsumerBase>) dealBean;
  11. }
  12. for (ConsumerEnum type : ConsumerEnum.values()) {
  13. Class<AbstractConsumerBase> clazz = type.getDealBean();
  14. AbstractConsumerBase person = clazz.newInstance();
  15. dealMap.put(type.getTopic(), person);
  16. }

方式二-直接new方式

  1. DISPATCH_INFO(RetryBizEnum.DISPATCH_INFO.getValue(), FullBizCodeEnum.D1003, OrderSyncDispatchInfoConsumer.TOPIC, new OrderSyncDispatchInfoConsumer());
  2. /**
  3. * 处理类bean
  4. */
  5. private final AbstractConsumerBase dealBean;
  6. ConsumerEnum(int bizType, FullBizCodeEnum bizCode, String topic, AbstractConsumerBase dealBean) {
  7. this.bizType = bizType;
  8. this.bizCode = bizCode;
  9. this.topic = topic;
  10. this.dealBean = (AbstractConsumerBase) dealBean;
  11. }
  12. for (ConsumerEnum type : ConsumerEnum.values()) {
  13. dealMap.put(type.getTopic(), type.getDealBean());
  14. }

后面使用静态工厂方式进行封装

  1. package com.yougou.ordercenter.web.listener.kafka.topic.base;
  2. import com.yougou.framework.logger.Logger;
  3. import com.yougou.framework.logger.LoggerFactory;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. /**
  7. * 静态工厂模式
  8. *
  9. * @author david
  10. * @site www.belle.net.cn
  11. * @company 百丽国际
  12. * @Date 创建时间:2022-04-13 21:36
  13. */
  14. public class ConsumerFactory {
  15. private static final Logger logger = LoggerFactory.getLogger(ConsumerFactory.class);
  16. // 把topic对应的具体处理类,关系映射
  17. private static final Map<String, AbstractConsumerBase> dealMap = new HashMap<>(ConsumerEnum.values().length);
  18. static {
  19. try {
  20. for (ConsumerEnum type : ConsumerEnum.values()) {
  21. dealMap.put(type.getTopic(), type.getDealBean());
  22. }
  23. } catch (Exception e) {
  24. logger.error("实例化ConsumerFactory工厂类异常" + e.getMessage(), e);
  25. }
  26. }
  27. /**
  28. * 通过topic获取具体实现类
  29. *
  30. * @param topic
  31. * @return
  32. */
  33. public static AbstractConsumerBase create(String topic) {
  34. return dealMap.get(topic);
  35. }
  36. }