支付业务优化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 往下写,如果十几家怎么办?所以这个要进行优化。

优化步骤

创建一个支付接口,提供两个方法

<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 判断了。