策略模式在支付場景中的最佳實踐

版本

  • 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章