定义业务枚举
java
@Getter
public enum BizTypePrefixEnum {
PAYMENT("PMT", "消费"),
RECHARGE("RCH", "充值"),
WITHDRAWAL("WDW", "提现"),
REFUND("RFD", "退款"),
RED_PACKET_PAY("RP", "红包支付"),
;
private final String code;
private final String desc;
BizTypePrefixEnum(String code, String desc) {
this.code = code;
this.desc = desc;
}
public static BizTypePrefixEnum getStartsWith(String outTradeNo) {
for (BizTypePrefixEnum bizTypePrefixEnum : BizTypePrefixEnum.values()) {
if (outTradeNo.startsWith(bizTypePrefixEnum.getCode())) {
return bizTypePrefixEnum;
}
}
return null;
}
}
定义策略接口
java
public interface NotifyProcessHandler {
/**
* 支付回调参数
*
* @param req
*/
void process(NotifyPaymentReq req);
/**
* 业务类型
*
* @return
*/
BizTypePrefixEnum getBizType();
}
不同枚举业务,分别定义实现类
java
@Slf4j
@Service
public class PaymentNotifyHandler implements NotifyProcessHandler {
@Override
public void process(NotifyPaymentReq req) {
// todo 消费支付结果处理
}
@Override
public BizTypePrefixEnum getBizType() {
return BizTypePrefixEnum.PAYMENT;
}
}
java
@Slf4j
@Service
public class RechargeNotifyHandler implements NotifyProcessHandler {
@Override
public void process(NotifyPaymentReq req) {
// todo 充值支付结果处理
}
@Override
public BizTypePrefixEnum getBizType() {
return BizTypePrefixEnum.RECHARGE;
}
}
...等等其他枚举处理类
创建工厂,初始化加载策略类
java
@Component
public class NotifyProcessFactory implements InitializingBean {
@Autowired
private List<NotifyProcessHandler> notifyProcessHandlerList;
private final Map<BizTypePrefixEnum, NotifyProcessHandler> handlerMap = new HashMap<>();
@Override
public void afterPropertiesSet() throws Exception {
for (NotifyProcessHandler notifyProcessHandler : notifyProcessHandlerList) {
handlerMap.put(notifyProcessHandler.getBizType(), notifyProcessHandler);
}
}
public NotifyProcessHandler getHandler(BizTypePrefixEnum bizType) {
return handlerMap.get(bizType);
}
}
注入工厂,实现处理策略
java
@Autowired
private NotifyProcessFactory notifyProcessFactory;
NotifyProcessHandler handler = notifyProcessFactory.getHandler(BizTypePrefixEnum.getStartsWith(req.getOutTradeNo()));
handler.process(req);