策略模式在支付场景中的最佳实践

版本

  • SpringBoot:2.2.5.RELEASE
  • Jdk:1.8
  • Maven:3.5.2
  • Idea:2019.3

准备

模板方法模式在支付场景中的最佳实践

食用

0:融入策略模式
支付场景中加入模板方法模式后,还有一点可以改进的地方:选择支付方式,在“模板方法模式在支付场景中的最佳实践”一文中我们发现,发起支付时,我们需要手动选择对应的支付方式来发起支付,下面来看看如何根据传入的“支付方式”字段来自动匹配支付方式

/**
 * @author liujiazhong
 */
@Slf4j
@Component
public class PayStrategy implements InitializingBean {

    private static Map<Set<PaymentTypeEnum>, PayService> PAY_STRATEGY;

    @Autowired
    private BankPayService bankPayService;
    @Autowired
    private LocalPayService localPayService;

    @Override
    public void afterPropertiesSet() {
        HashMap<Set<PaymentTypeEnum>, PayService> temp = new HashMap<>(2);
        temp.put(Sets.newHashSet(LOCAL), localPayService);
        temp.put(Sets.newHashSet(BANK), bankPayService);
        PAY_STRATEGY = Collections.unmodifiableMap(temp);
    }

    protected final PayRespBO doPay(PayReqBO request) {
        PaymentTypeEnum paymentType = valueOf(request.getPaymentType());
        for (Map.Entry<Set<PaymentTypeEnum>, PayService> entry : PAY_STRATEGY.entrySet()) {
            if (entry.getKey().contains(paymentType)) {
                return entry.getValue().pay(request);
            }
        }
        throw new RuntimeException("no suitable payment type.");
    }

}

从代码中可以看出,我们新增了两种策略,PaymentTypeEnum.LOCAL对应localPayService,PaymentTypeEnum.BANK对应bankPayService,只要传入对应的支付方式,“entry.getValue().pay(request)”这里就可以使用对应的支付方式完成支付
1:提供统一入口
接下来我们只需要提供一个统一的支付入口就行了

/**
 * @author liujiazhong
 */
@Slf4j
@Service
public class GardeniaPayService extends PayStrategy {

    public PayRespBO pay(PayReqBO request) {
        return doPay(request);
    }

}

2:结果测试

/**
 * @author liujiazhong
 * @date 2020/4/15 15:51
 */
@Slf4j
@RestController
public class DemoController {

    private final GardeniaPayService gardeniaPayService;

    public DemoController(GardeniaPayService gardeniaPayService) {
        this.gardeniaPayService = gardeniaPayService;
    }

    @GetMapping("pay/{type}")
    public void pay(@PathVariable String type) {
        gardeniaPayService.pay(PayReqBO.builder().orderId(100001L).orderCode("TEST100001").paymentType(type).userId(1001L).build());
    }
    
}

测试结果与“模板方法模式在支付场景中的最佳实践”中的结果一致

链接

策略模式:https://zh.wikipedia.org

发布了36 篇原创文章 · 获赞 19 · 访问量 2418

猜你喜欢

转载自blog.csdn.net/momo57l/article/details/105555797