在多支付渠道中这个设计模式无敌好用!

265 阅读2分钟

假设我们有一个电商平台,需要支持多种支付方式。

通过策略模式来实现,管理不同的支付方式,并根据需求快速添加新的支付方式。

  1. 定义支付策略接口及其实现类:
java

// 支付策略接口
public interface PaymentStrategy {
    void pay(int amount);
}

// 支付宝支付策略的实现类
public class AlipayStrategy implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("使用支付宝支付" + amount + "元");
        // 模拟支付逻辑
    }
}

// 微信支付策略的实现类
public class WechatPayStrategy implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("使用微信支付" + amount + "元");
        // 模拟支付逻辑
    }
}

// 银联支付策略的实现类
public class UnionPayStrategy implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("使用银联支付" + amount + "元");
        // 模拟支付逻辑
    }
}
  1. 支付上下文类:
java

public class PaymentContext {
    private PaymentStrategy strategy;

    public PaymentContext(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void executePayment(int amount) {
        strategy.pay(amount);
    }
}
  1. 订单类:
java

public class Order {
    private int orderId;
    private int amount;
    private String paymentType;

    public Order(int orderId, int amount, String paymentType) {
        this.orderId = orderId;
        this.amount = amount;
        this.paymentType = paymentType;
    }

    public int getOrderId() {
        return orderId;
    }

    public int getAmount() {
        return amount;
    }

    public String getPaymentType() {
        return paymentType;
    }
}
  1. 订单服务类:
java

@Service
public class OrderService {
    private Map<String, PaymentStrategy> strategies = new HashMap<>();

    @Autowired
    private ApplicationContext context;

    @PostConstruct
    public void init() {
        Map<String, PaymentStrategy> beans = context.getBeansOfType(PaymentStrategy.class);
        strategies.putAll(beans);
    }

    public void processOrder(Order order) {
        PaymentStrategy strategy = strategies.get(order.getPaymentType());
        if (strategy != null) {
            System.out.println("处理订单:" + order.getOrderId());
            strategy.pay(order.getAmount());
        } else {
            throw new IllegalArgumentException("无效的支付类型:" + order.getPaymentType());
        }
    }
}
  1. Spring配置文件(application.yml):
yaml

payment:
  strategies:
    - name: alipayStrategy
      className: com.example.strategy.AlipayStrategy
    - name: wechatPayStrategy
      className: com.example.strategy.WechatPayStrategy
    - name: unionPayStrategy
      className: com.example.strategy.UnionPayStrategy
  1. 测试类:
java

public class PaymentApplication {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        OrderService orderService = context.getBean(OrderService.class);

        // 创建订单
        Order order1 = new Order(1, 100, "alipayStrategy");
        Order order2 = new Order(2, 200, "wechatPayStrategy");
        Order order3 = new Order(3, 300, "unionPayStrategy");

        // 处理订单
        orderService.processOrder(order1); // 输出:使用支付宝支付100元
        orderService.processOrder(order2); // 输出:使用微信支付200元
        orderService.processOrder(order3); // 输出:使用银联支付300元
    }
}
  1. AppConfig类:
java

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
    // 其他配置
}

PS:我们通过定义支付策略接口及其实现类、创建支付上下文类、订单类以及订单服务类,实现了对不同支付方式的灵活管理和调用。

Spring配置文件和测试类则展示了如何在Spring框架中集成和测试策略模式。

除了基本的支付逻辑,还展示了如何通过Spring框架自动加载和管理支付策略,进一步增强了灵活性和可扩展性。

我个人建议大家在日常开发中多多尝试使用策略模式,特别是在需要处理多种类似操作的场景下,这个设计模式是23种设计模式中除了单例、工厂以外为数不多的实用容易理解的模式了。

最后说一句(求关注!别白嫖!)

如果这篇文章对您有所帮助,或者有所启发的话,求一键三连:点赞、转发、在看。

关注公众号:woniuxgg,在公众号中回复:笔记  就可以获得蜗牛为你精心准备的java实战语雀笔记,回复面试、开发手册、有超赞的粉丝福利!