需求
- 传参String payType = wechat 使用微信支付
- 传参String payType = ali 使用支付宝支付
- 代码不允许出现if-else
思路
把支付当作一个行为,代码中当作一个接口,payService。2个实现类,分别是微信支付实现类WeChatPayServiceImpl,支付宝支付实现类AliPayImpl。利用多态+工厂根据支付类型获取对应的实现类
代码如下
支付接口payService
public interface PayService {// 下单接口String jsapi(Map<String,Object> map);
}
微信支付实现类WeChatPayServiceImpl
@Slf4j
@Service
@CacheConfig(cacheNames = "weChatPay")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class WeChatPayServiceImpl implements PayService {@Overridepublic String jsapi(Map<String, Object> map) {return "微信支付";}
}
支付宝支付实现类AliPayImpl
@Slf4j
@Service
@CacheConfig(cacheNames = "aliPay")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AliPayImpl implements PayService {@Overridepublic String jsapi(Map<String, Object> map) {return "支付宝支付";}}
工厂
public class PayFactory {private static final Map<String, PayService> PayFactoryMap = new HashMap<>();static {PayFactoryMap.put("wechat", new WeChatPayServiceImpl());PayFactoryMap.put("ali", new AliPayImpl());}public static PayService getPayment(String payType) {PayService payService = PayFactoryMap.get(payType);if (null == payService) throw new RuntimeException("支付类型错误");return payService;}
}
具体实现
偷懒直接在controller实现
@ApiOperation(value = "订单支付接口")@GetMapping("/pay")public ResponseEntity pay(String payType){PayService medalService = PayFactory.getPayment(payType);String jsapi = medalService.jsapi(null);log.info(jsapi);return new ResponseEntity<>(jsapi,HttpStatus.OK);}
测试结果
总结&建议
感觉好像不是利用策略者模式
建议还是用工厂实现,不要用枚举