目录
- @Service
- public interface PayStrategy {
- Boolean pay(Paybody paybody);
- }
-
- public class WxPayStrategy implements PayStrategy {
- @Override
- public Boolean pay(Paybody paybody) {
- // 模拟微信支付过程
- System.out.println("微信支付失败!");
- return false;
- }
- }
-
- public class ZfbPayStrategyPay implements PayStrategy{
- @Override
- public Boolean pay(Paybody paybody) {
- // 模拟支付宝支付过程
- System.out.println("支付宝支付成功!");
- return true;
- }
- }
-
- @Data
- public class Paybody {
- /**
- * 支付类型
- * ZFB 支付宝
- * WX 微信
- */
- private String type;
- /**
- * 商品
- */
- private String product;
- }
- /**
- * 支付策略工厂
- */
- public class StrategyFactory {
- public static PayStrategy getPayStrategy(String type){
- // 1.通过枚举中的type获取对应value
- String value = EnumUtil.getFieldBy(PayStrategyEnum::getValue, PayStrategyEnum::getType, type);
- // 2.使用反射创建对应的策略类
- PayStrategy payStrategy = ReflectUtil.newInstance(value);
- return payStrategy;
- }
- }
-
- /**
- * 支付策略枚举
- */
- public enum PayStrategyEnum {
- ZFB("ZFB","com.example.demo.pay.stragety.ZfbPayStrategyPay"),
- WX("WX","com.example.demo.pay.stragety.WxPayStrategy")
- ;
- String type;
- String value;
- PayStrategyEnum(String type,String value){
- this.type = type;
- this.value = value;
- }
-
- public String getValue() {
- return value;
- }
-
- public String getType() {
- return type;
- }
-
- }
-
起承上启下封装作用,屏蔽高层模块对策略、算法的直接访问,封装可能存在的变化。
- public class PayContext {
- private PayStrategy payStrategy;
-
- public PayContext(PayStrategy payStrategy) {
- this.payStrategy = payStrategy;
- }
-
- public Boolean execute(Paybody paybody) {
- return this.payStrategy.pay(paybody);
- }
- }
- public class StrategyFacade {
- public static Boolean Pay(Paybody paybody){
- // 1.获取策略对象
- PayStrategy payStrategy = StrategyFactory.getPayStrategy(paybody.getType());
- // 2.获取策略上下文
- PayContext payContext = new PayContext(payStrategy);
- // 3.进行扣款
- return payContext.execute(paybody);
- }
- }
- @RestController
- public class PayController {
-
- @Autowired
- private PayService payService;
-
- @PostMapping("/pay")
- public Boolean pay(@RequestBody Paybody paybody){
- return payService.Pay(paybody);
- }
- }
-
-
- @Service
- public class PayService {
- public Boolean Pay(Paybody paybody){
- if (!EnumUtil.contains(PayStrategyEnum.class, paybody.getType())) {
- throw new IllegalArgumentException("不支持的支付方式!");
- }
- return StrategyFacade.Pay(paybody);
- }
- }