支付業務優化else if 代碼


背景

最近在做項目的時候,需要接入支付。由於接入第三方支付而且還不知止一家,需要接入很多家。比如說支付寶、微信、富友支付等。每家支付都一個回調。現如今的代碼,根據不同的第三方支付一大堆else if判斷。現如今代碼如下:

<code> public PayResponse pay(PayRequestType payRequestType) {
        PayTypeEnum payType = PayTypeEnum.para(payRequestType.getPayType());
        if (payType == PayTypeEnum.ALIPAY) {
            return alipayService.pay(payRequestType);
        } else if (payType == PayTypeEnum.WEIXIN) {
            return weixinPayService.pay(payRequestType);
        } else if (payType == PayTypeEnum.LIANLIAN) {
            return lianlianPayService.pay(payRequestType);
        }
        // 其他支付方式
        return null;
    }
/<code>

如果以後要接入其他的支付方式,然後就要接著else if 往下寫,如果十幾家怎麼辦?所以這個要進行優化。

優化步驟

  1. 創建一個支付接口,提供兩個方法
<code>public interface Pay {

    PayResponse pay(PayRequestType payRequestType);

    /**
     * 每家支付方式對應的類型
     * @return
     */
    PayTypeEnum getPayType();
}```
每家支付都去實現這個類:比如微信支付

```java
@Component
public class WeixinPayService implements Pay {
    @Override
    public PayResponse pay(PayRequestType payRequestType) {
        return null;
    }

    @Override
    public PayTypeEnum getPayType() {
        return PayTypeEnum.WEIXIN;
    }
/<code>

然後準備一個工廠把那些判斷if else 消除掉

<code>public final class PayFactory {
    private PayFactory() {
    }
    public static Map PAYMAP = new ConcurrentHashMap();
    static {
        Map beansOfType = ApplicationContextHelper.getBeansOfType(Pay.class);
        for (Map.Entry entry : beansOfType.entrySet()) {
            Pay pay = entry.getValue();
            PAYMAP.put(pay.getPayType(), pay);
        }
    }

    public static Pay getPay(PayTypeEnum payTypeEnum){
        return  PAYMAP.get(payTypeEnum);
    }
/<code>

spring獲取bean幫助類

<code>
@Component
public class ApplicationContextHelper implements ApplicationContextAware {

   public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    public static   T getBean(Class clazz) {
        return applicationContext.getBean(clazz);
    }

    public static  Map getBeansOfType(Class clazz) {
        return applicationContext.getBeansOfType(clazz);
    }
/<code>

優化後代碼

<code>  public PayResponse pay2(PayRequestType payRequestType) {
        PayTypeEnum payType = PayTypeEnum.para(payRequestType.getPayType());
       return PayFactory.getPay(payType).pay(payRequestType);
    }
/<code>

後續新增支付方式的話,只要新增枚舉類型、然後實現pay接口就可以了。沒有了複雜的if else 判斷了。


分享到:


相關文章: