java解决if-else多分支技巧

1、分支逻辑提前return

    if (CollectionUtils.isEmpty(newDataList)) {
        // 提前判断,返回业务逻辑
        return;
    }
    TestCodeData newData = newDataList.stream().filter(p -> {
        if (p.getIsHoliday() == 1) {
            return true;
        }
        return false;
    }).findFirst().orElse(null);

2、switch case

OuterPlatformCodeEnum codeEnum = OuterPlatformCodeEnum.getByCode(req.getExtChannelCode());
switch (codeEnum) {
	case ZKL:
		return zklPushAuditResultService.afterSaleAudit(req);
	case REDBOOK:
		return @@@;
	case TIKTOK:
		return @@@;
	case KWAI:
		return @@@;
	default:
		log.error("afterSaleAudit当前渠道还未对接{}", JSON.toJSONString(req));
		return Response.ok();
}

3、枚举

public enum TimeEnum {

    AM("am", "上午") {
        @Override
        public void setCity(TestCodeData data, List<TestCodeData> oldDataList) {
            TestCodeData po = oldDataList.stream().filter(p -> p.getStartTime() == 0
                    && (p.getEndTime() == 12 || p.getEndTime() == 24)).findFirst().orElse(null);
            if (null != po) {
                data.setCity(po.getCity());
            }
        }
    },
    PM("pm", "下午") {
        @Override
        public void setCity(TestCodeData data, List<TestCodeData> oldCollect) {
            TestCodeData po = oldCollect.stream().filter(
                    p -> (p.getStartTime() == 12 || p.getStartTime() == 0)
                            && p.getEndTime() == 24).findFirst().orElse(null);
            if (po != null) {
                data.setCity(po.getCity());
            }
        }
    },
    DAY("day", "全天") {
        @Override
        public void setCity(TestCodeData data, List<TestCodeData> oldCollect) {
            TestCodeData po = oldCollect.stream().filter(
                    p -> p.getStartTime() == 0 && p.getEndTime() == 24).findFirst().orElse(null);
            if (po == null) {
                po = oldCollect.stream().filter(
                        p -> p.getStartTime() == 0 && p.getEndTime() == 12).findFirst().orElse(null);
            }
            if (po == null) {
                po = oldCollect.stream().filter(
                        p -> p.getStartTime() == 12 && p.getEndTime() == 24).findFirst().orElse(null);
            }
            if (po != null) {
                data.setCity(po.getCity());
            }
        }
    },
    HOUR("hour", "小时") {
        @Override
        public void setCity(TestCodeData data, List<TestCodeData> oldCollect) {
            TestCodeData po = oldCollect.stream().filter(
                    e -> e.getTimeUnit().equals(Integer.valueOf(1))).findFirst().orElse(null);
            if (po != null) {
                data.setCity(po.getCity());
            }
        }
    };
    public TimeEnum valueOf(String code) {
         TimeEnum [] values = values();
            for (TimeEnum value : values) {
                if (code.equals(value.getCode())) {
                    return value.getName();
                }
            }
    }

    public abstract void setCity(TestCodeData data, List<TestCodeData> oldCollect);

    private String code;
    private String desc;

    TimeEnum(String code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

for (TestCodeData data : newCollect) {
      String code = "am";  // 这里假设 code 变量是从 data 中获取的
      TimeEnum.valueOf(code).setCity(data, oldCollect);
}

4、函数式接口

@Service
public class KwaiAfterSaleAuditService {
    private static final Logger logger = LoggerFactory.getLogger(KwaiAfterSaleAuditService.class);
    private Map<Integer, BiFunction<KwaiExtchCfg, AfterSaleAuditReq, Response<Boolean>>> sourceMap = new HashMap<>();

    @Resource
    private KwaiApiService kwaiApiService;

    @PostConstruct
    private void dispatcher() {
        sourceMap.put(10, this::approve);
        sourceMap.put(-10, this::reject);
    }

    public Response<Boolean> auditDeal(KwaiExtchCfg kwaiExtchCfg, AfterSaleAuditReq req) {
        BiFunction<KwaiExtchCfg, AfterSaleAuditReq, Response<Boolean>> source = sourceMap.get(req.getAuditResult());
        return source.apply(kwaiExtchCfg, req);
    }

    private Response<Boolean> approve(KwaiExtchCfg kwaiExtchCfg, AfterSaleAuditReq req) {
        OpenSellerOrderRefundReturngoodsApproveResponse response = kwaiApiService.returnGoodsApprove(kwaiExtchCfg, req, 788L);
        logger.info("{}, OpenSellerOrderRefundReturngoodsApproveResponse:{}", req.getReturnsId(), JSON.toJSONString(response));
        if (null != response && response.getResult() == 1) {
            return Response.ok(true);
        } else {
            return Response.fail(response != null ? response.getErrorMsg() : "退货审核结果推送失败,返回null");
        }
    }

    private Response<Boolean> reject(KwaiExtchCfg kwaiExtchCfg, AfterSaleAuditReq req) {
        OpenRefundRejectReasonResponse reasonResponse = kwaiApiService.rejectReason(kwaiExtchCfg, Long.parseLong(req.getReturnsId()));
        logger.info("reasonResponse:{}", JSON.toJSONString(reasonResponse));
        OpenRefundRejectResponse response = kwaiApiService.refundReject(kwaiExtchCfg, Long.parseLong(req.getReturnsId()), 12, 788L);
        logger.info("{}, OpenRefundRejectResponse:{}", req.getReturnsId(), JSON.toJSONString(response));
        if (null != response && response.getResult() == 1) {
            return Response.ok();
        } else {
            return Response.fail(response != null ? response.getErrorMsg() : "退货审核结果推送失败,返回null");
        }
    }
}

5、设计模式
工厂模式

自定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtchSynData {
    String[] value();
}

工厂类
@Component
public class McoServiceFactory {

    private static final Logger logger = LoggerFactory.getLogger(McoServiceFactory.class);

    /**
     * 数据日志及备份 service注册表
     */
    private Map<String, ExtchDataSaveService> extchDataSaveServiceMap = Maps.newConcurrentMap();

    @PostConstruct
    private void init() {
        initExtchDataSaveService();
    }

    /**
     * 初始化数据日志及备份 service注册表
     */
    private void initExtchDataSaveService() {
        Map<String, ExtchDataSaveService> result = SpringBeanUtil.getApplicationContext().getBeansOfType(ExtchDataSaveService.class);
        if (CollectionUtils.isEmpty(result)) {
            logger.warn("初始化获取失败,没有发现策略实现 bean。");
            throw new RuntimeException("初始化数据日志及备份");
        }
        for (Map.Entry<String, ExtchDataSaveService> entry : result.entrySet()) {
            String beanName = entry.getKey();
            ExtchDataSaveService value = entry.getValue();

            ExtchSynData dataAnnotation = value.getClass().getAnnotation(ExtchSynData.class);
            if (null != dataAnnotation) {
                for (String string : dataAnnotation.value()) {
                    extchDataSaveServiceMap.put(string, value);
                }
            } else {
                logger.info("初始化,operateType is null, bean:{}", beanName);
            }
        }
    }
    public ExtchDataSaveService getExtchDataSaveService(String operateType) {
        if (operateType == null) {
            logger.error("[McoServiceFactory.getExtchDataSaveService] the input param is null, return [null].");
            return null;
        }
        return extchDataSaveServiceMap.get(operateType);
    }
}
// 方法调用
ExtchDataSaveService extchDataSaveService = mcoServiceFactory.getExtchDataSaveService(methodName);
Response<Boolean> response = extchDataSaveService.beforeDataHandler(className, methodName, joinPoint.getArgs());

模板模式:

抽象模板类
@Service
public abstract class BaseMessageService {

    private static final Logger logger = LoggerFactory.getLogger(BaseMessageService.class);

    /**
     * Description: 数据处理
     * Date: 2021/9/15 11:17
     * @Param: [parentMessage] 消息体
     * @Return: com.gome.retail.boot.model.Response<java.lang.Boolean>
     */
    protected abstract Response<Boolean> dataHandle(KwaiParentMessage parentMessage);

    /**
     * Description: 任务执行 先处理数据再进行业务处理
     * Date: 2021/9/15 11:13
     * @Param: [parentMessage]
     * @Return: com.gome.retail.boot.model.Response<java.lang.Boolean>
     */
    public Response<Boolean> execute(KwaiParentMessage parentMessage) {
        Response<Boolean> kwaiParentMessageResponse = dataHandle(parentMessage);
        if (!kwaiParentMessageResponse.isOk()) {
            logger.error(kwaiParentMessageResponse.getMsg());
            return Response.fail("参数解析失败");
        }
        return bussiness(parentMessage);
    }

    /**
     * Description: 业务处理
     * Date: 2021/9/15 11:17
     * @Param: [parentMessage]
     * @Return: com.gome.retail.boot.model.Response<java.lang.Boolean>
     */
    protected abstract Response<Boolean> bussiness(KwaiParentMessage parentMessage);
}

// 分支业务类
@KwaiEvent({"kwaishop_order_statusChange"})
@Service
public class KwaiOrderMessageService extends BaseMessageService {

    private static final Logger logger = LoggerFactory.getLogger(KwaiOrderMessageService.class);

    @Resource
    private KwaiApiService kwaiApiService;

    @Resource
    private KwaiExtchCfgService kwaiExtchCfgService;

    @Resource
    private KwaiMcoOrderService kwaiMcoOrderService;

    @Override
    protected Response<Boolean> dataHandle(KwaiParentMessage parentMessage) {
        try {
            if (StringUtils.isEmpty(parentMessage.getInfo())) {
                logger.error("缺少消息详细信息:{}", JSON.toJSONString(parentMessage));
                return Response.fail("缺少消息体");
            }
            KwaiMessageOrder kwaiMessageOrder = JSON.parseObject(parentMessage.getInfo(), KwaiMessageOrder.class);
            parentMessage.setKwaiMessage(kwaiMessageOrder);
        } catch (Exception e) {
            logger.error("参数解析失败message:{}", JSON.toJSONString(parentMessage), e);
            return Response.fail("参数解析失败");
        }
        return Response.ok();
    }

    @Override
    protected Response<Boolean> bussiness(KwaiParentMessage parentMessage) {
        KwaiExtchCfg kwaiExtchCfg = kwaiExtchCfgService.obtainCacheExtchCfg(String.valueOf(parentMessage.getUserId()));
        KwaiMessageOrder kwaiMessageOrder = (KwaiMessageOrder) parentMessage.getKwaiMessage();
        logger.info("消息单个订单获取 oid:{}", kwaiMessageOrder.getOid());
        if (!(Constants.PULL_ORDER_STATUS_30 == kwaiMessageOrder.getStatus()
                || Constants.PULL_ORDER_STATUS_40 == kwaiMessageOrder.getStatus()
                || Constants.PULL_ORDER_STATUS_50 == kwaiMessageOrder.getStatus()
                || Constants.PULL_ORDER_STATUS_70 == kwaiMessageOrder.getStatus())) {
            return Response.ok();
        }
        OpenOrderCursorListResponse response = kwaiApiService.obtainOrderDetail(kwaiMessageOrder.getOid(), kwaiExtchCfg);
        logger.info("消息单个订单获取返回 oid:{} response:{}", kwaiMessageOrder.getOid(), JSON.toJSONString(response));
        if (response.isSuccess() && null != response.getData() && null != response.getData().getOrderList() && response.getData().getOrderList().length > 0) {
            OrderList orderList = response.getData().getOrderList()[0];
            Response<Boolean> singleResponse = kwaiMcoOrderService.singleOrderByOrderList(orderList, kwaiExtchCfg, null);
            logger.info("消息单个订单处理结果oid:{}, res:{}", kwaiMessageOrder.getOid(), JSON.toJSONString(singleResponse));
        }
        return Response.ok();
    }
}

// 缓存服务类工厂
@Component
public class KwaiAcceptServiceFactory {

    private static final Logger logger = LoggerFactory.getLogger(KwaiAcceptServiceFactory.class);

    /**
     * 消息service注册表
     */
    private Map<String, BaseMessageService> messageServiceMap;

    @PostConstruct
    private void init() {
        messageServiceMap = new HashMap<>(8);
        initMessageService();
    }

    /**
     * 初始化service注册表
     */
    private void initMessageService() {
        Map<String, BaseMessageService> result = SpringBeanUtil.getApplicationContext().getBeansOfType(BaseMessageService.class);
        if (CollectionUtils.isEmpty(result)) {
            logger.warn("初始化获取失败,没有发现策略实现 bean。");
            throw new RuntimeException("初始化消息处理类失败");
        }
        for (Map.Entry<String, BaseMessageService> entry : result.entrySet()) {
            String beanName = entry.getKey();
            BaseMessageService value = entry.getValue();

            KwaiEvent dataAnnotation = value.getClass().getAnnotation(KwaiEvent.class);
            if (null != dataAnnotation) {
                for (String string : dataAnnotation.value()) {
                    messageServiceMap.put(string, value);
                }
            } else {
                logger.info("初始化,operateType is null, bean:{}", beanName);
            }
        }
    }

    /**
     * Description: 获取消息处理类
     * Date: 2021/9/14 19:21
     *
     * @Param: [operateType]
     * @Return: cn.com.gome.scot.alamein.mco.kwai.job.business.domain.message.BaseMessageService
     */
    public BaseMessageService obtainMessageService(String operateType) {
        if (operateType == null) {
            logger.error("[McoServiceFactory.getExtchDataSaveService] the input param is null, return [null].");
            return null;
        }
        return messageServiceMap.get(operateType);
    }
}
posted @ 2022-04-13 11:25  倔强的老铁  阅读(464)  评论(0编辑  收藏  举报