策略模式业务实战

一、策略模式实现任务分发

1.新建策略接口

bash 复制代码
package com.ehe.elder.strategy;

public interface ElderJobOrderStrategy {
    void notifyMethod(String outTradeNo);
}

2.新建策略实现类

bash 复制代码
@Slf4j
@Component
public class ElderJobOrderGranter implements ElderJobOrderStrategy {

    public static final String ELDET_JOB_ORDER = "FW-";

    @Override
    public void notifyMethod(String outTradeNo) {
		//业务处理
	}
}
bash 复制代码
package com.ehe.elder.granter.order;

import com.ehe.elder.strategy.ElderJobOrderStrategy;
import org.springframework.stereotype.Component;

@Component
public class WeiLaoOrderGranter implements ElderJobOrderStrategy {

    public static final String WEI_LAO_TYPE = "";

    @Override
    public void notifyMethod(String outTradeNo) {
		//业务实现
    }
}

3.新建策略工厂

bash 复制代码
package com.ehe.elder.builder;

import com.ehe.core.exception.ResponseInfoException;
import com.ehe.core.http.HttpResponseStatus;
import com.ehe.core.http.ResponseInfo;
import com.ehe.core.util.SpringUtil;
import com.ehe.elder.granter.order.ElderJobOrderGranter;
import com.ehe.elder.granter.order.WeiLaoOrderGranter;
import com.ehe.elder.granter.order.YiJianTongOrderGranter;
import com.ehe.elder.strategy.ElderJobOrderStrategy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ElderJobOrderBuilder {

    private static Map<String, ElderJobOrderStrategy> strategyMap = new ConcurrentHashMap<>();
    static {
        strategyMap.put(ElderJobOrderGranter.ELDET_JOB_ORDER, SpringUtil.getBean(ElderJobOrderGranter.class));
        strategyMap.put(WeiLaoOrderGranter.WEI_LAO_TYPE,SpringUtil.getBean(WeiLaoOrderGranter.class));
    }
    public static ElderJobOrderStrategy getVolunteerType(String orderType){
        ElderJobOrderStrategy elderJobOrderStrategy = strategyMap.get(orderType);
        if (elderJobOrderStrategy == null) {
            throw ResponseInfoException.of(ResponseInfo.of(HttpResponseStatus.ORDER_PROCESS_NOT_EXISTS));
        } else {
            return elderJobOrderStrategy;
        }
    }
}

4.业务调用

bash 复制代码
ElderJobOrderBuilder.getVolunteerType(YiJianTongOrderGranter.YI_JIAN_TONG_ORDER).notifyMethod(outTradeNo);

二、元注解+策略管理器

1.策略接口

bash 复制代码
package com.ehe.elder.function.handler;

import com.ehe.elder.domain.ElderJobOrder;
import com.ehe.elder.function.param.PayPramInfo;
import java.io.Serializable;

public interface JobOrderHanlder<T,R> extends Serializable {

    void doHnalder(ElderJobOrder elderJobOrder, PayPramInfo payPramInfo);

}

2.策略管理中心

bash 复制代码
package com.ehe.elder.function.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.ehe.elder.domain.ElderJobOrder;
import com.ehe.elder.function.annotation.JobOrderDuty;
import com.ehe.elder.function.handler.JobOrderHanlder;
import com.ehe.elder.function.param.PayPramInfo;
import org.springframework.core.annotation.AnnotationUtils;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class HandleChainManager {

    private Map<String, List<JobOrderHanlder>> handleMap;

    public void setHandleMap(List<JobOrderHanlder> handlerList) {
        handleMap = handlerList
                .stream()
                .sorted(Comparator.comparingInt(h -> AnnotationUtils.findAnnotation(h.getClass(), JobOrderDuty.class).order()))
                .collect(Collectors.groupingBy(handler -> AnnotationUtils.findAnnotation(handler.getClass(), JobOrderDuty.class).type()));
    }

    public <T, R> void executeHandle(String type, ElderJobOrder t, PayPramInfo p) {
        List<JobOrderHanlder> handlers = handleMap.get(type);
        if (CollectionUtil.isNotEmpty(handlers)) {
            for (JobOrderHanlder<T, R> handler : handlers) {
                handler.doHnalder(t,p);
            }
        }
    }
}

3.策略实现类实现积分处理

bash 复制代码
import com.alibaba.fastjson.JSONObject;
import com.ehe.core.thread.LocalVariable;
import com.ehe.core.util.SpringUtil;
import com.ehe.core.util.TimeUtils;
import com.ehe.elder.domain.ElderJobOrder;
import com.ehe.elder.enumeration.ElderConstant;
import com.ehe.elder.function.annotation.JobOrderDuty;
import com.ehe.elder.function.param.PayPramInfo;
import com.ehe.elder.function.util.OrderInfoUtil;
import com.ehe.elder.service.PolicyServerTypeService;
import com.ehe.elder.service.TimeBankPushService;
import com.ehe.elder.util.ValidateIDCard;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@JobOrderDuty(type = "JOB_ORDER_HANDLER",order = 0)
public class IntegralChainHandler implements JobOrderHanlder{

    private static final long serialVersionUID = -4841388671717166795L;

    @Override
    public void doHnalder(ElderJobOrder elderJobOrder, PayPramInfo payPramInfo) {
      //业务处理
    }
}
bash 复制代码
package com.ehe.elder.function.handler;

import cn.hutool.core.math.Money;
import com.ehe.core.http.ResponseInfo;
import com.ehe.elder.domain.ElderJobOrder;
import com.ehe.elder.enumeration.ElderConstant;
import com.ehe.elder.function.annotation.JobOrderDuty;
import com.ehe.elder.function.param.PayPramInfo;
import com.ehe.elder.function.util.OrderInfoUtil;
import com.ehe.elder.util.OrderNumUtil;
import com.ehe.pay.manager.PayManager;
import com.ehe.pay.vo.PayOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Slf4j
@Service
@JobOrderDuty(type = "JOB_ORDER_HANDLER",order = 2)
public class VxPayChainHanler implements JobOrderHanlder{

    private static final long serialVersionUID = -3957365484396429232L;

    @Override
    public void doHnalder(ElderJobOrder elderJobOrder, PayPramInfo payPramInfo) {
    	//业务处理
    }
}

4.调用类

bash 复制代码
SpringUtil.getBean(HandleChainManager.class).executeHandle("JOB_ORDER_HANDLER",elderJobOrder,payPramInfo);

三、反射扫描策略接口

1.策略接口

bash 复制代码
package com.ehe.elder.strategy;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public interface PayStrategy {

    /**
     * 支付前准备支付参数
     */
    Map<String,String> prePay(Map<String, Object> map);

    /**
     * 支付后处理支付回调结果
     */
    String afterPay(HttpServletRequest request);

}

2.策略接口中间层处理公共逻辑

bash 复制代码
package com.ehe.elder.service.impl;
import com.ehe.elder.factory.PayStrategyFactory;
import com.ehe.elder.service.AbstractPayService;
import com.ehe.elder.strategy.PayStrategy;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Service
public class PayServiceImpl extends AbstractPayService {

    /**
     * 支付前准备支付参数
     */
    @Override
    public Map<String,String> prePay(Map<String, Object> map) {
        PayStrategy payStrategy = PayStrategyFactory.getStrategy(this.payType);
        if (payStrategy == null) {
            throw new RuntimeException("没有%s类型的支付策略...n"+this.payType);
        }
        return payStrategy.prePay(map);
    }

    /**
     * 支付后处理支付回调结果
     */
    @Override
    public String afterPay(HttpServletRequest request) {
        PayStrategy payStrategy = PayStrategyFactory.getStrategy(this.payType);
        return payStrategy.afterPay(request);
    }
}

package com.ehe.elder.service;
import com.ehe.elder.strategy.PayStrategy;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

//@Scope()可以设置原型模式
public abstract class AbstractPayService implements PayStrategy {

    protected String payType;

    /**
     * 支付
     */
    public Map<String,String> pay(String payType, Map<String, Object> map) {
        this.payType = payType;
        Map<String,String> resultMap = prePay(map);
        if (resultMap != null) {
            return resultMap;
        } else {
            return null;
        }
    }

    public String notifyPay(String payType, HttpServletRequest request) {
        this.payType = payType;
        return afterPay(request);
    }
}

3.策略业务处理接口

bash 复制代码
package com.ehe.elder.granter.pay;

import com.alibaba.excel.util.DateUtils;
import com.ehe.core.annotation.Pay;
import com.ehe.core.util.TimeUtils;
import com.ehe.elder.domain.ElderJobOrderPayParam;
import com.ehe.elder.enumeration.ElderConstant;
import com.ehe.elder.enumeration.RedisKeyConstant;
import com.ehe.elder.service.*;
import com.ehe.elder.strategy.PayStrategy;
import com.ehe.pay.manager.AliPayManager;
import com.ehe.setting.manager.PropertySettingManager;
import com.google.gson.Gson;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 支付宝支付
 */
@Slf4j
@Service
@Pay("orderAliPay")
//@ConditionalOnMissingBean(name = "elderOrderAliPay")
public class ElderOrderAliPay implements PayStrategy {

    @Override
    public Map<String,String> prePay(Map<String, Object> map) {
        try {
            log.info("开始支付宝支付,请求参数:{}",map);
            log.info("支付宝预下单结束,结果:{}",result);
            return hashMap;
        }catch (Exception e){
            log.info("支付宝下单异常:{}",e.getMessage());
            return null;
        }
    }

    @SneakyThrows
    @Override
    public String afterPay(HttpServletRequest request) {
        log.info("服务工单-支付宝回调=日期:{}", TimeUtils.ldtToStandardString(LocalDateTime.now()));
        return ElderConstant.SUCCESS_LOWER;
    }

}

4.业务调用

bash 复制代码
@Slf4j
@RestController
public class ElderJobOrderControllerImpl
    /** 支付策略 service  */
    @Autowired
    private AbstractPayService payService;
    
    Map<String,String> mapv =  payService.pay("orderVchatPay",map);
}
相关推荐
gjh12081 天前
设计模式:工厂方法模式和策略模式
设计模式·工厂方法模式·策略模式
liang89991 天前
设计模式之策略模式(Strategy)
设计模式·策略模式
修道-03231 天前
【JAVA】二、设计模式之策略模式
java·设计模式·策略模式
Jack黄从零学c++2 天前
设计模式——策略模式(c++)
c++·设计模式·策略模式
南城花随雪。3 天前
Spring框架之策略模式 (Strategy Pattern)
java·spring·策略模式
Fre丸子_3 天前
设计者模式之策略模式
c++·策略模式
超越不平凡3 天前
Spring Plugin与策略模式:打造动态可扩展的应用
spring·策略模式·spring plugin
G皮T4 天前
【设计模式】行为型模式(二):策略模式、命令模式
java·设计模式·策略模式·命令模式·command·strategy
7年老菜鸡7 天前
策略模式(C++)三分钟读懂
c++·qt·策略模式
也无晴也无风雨7 天前
代码中的设计模式-策略模式
设计模式·bash·策略模式