策略模式

推荐阅读:策略设计模式

介绍

假设有一个支付系统,需要支持使用不同的支付方式(策略),我们可以抽象出一个策略接口,然后定义具体的策略类来实现该接口。

策略接口

public interface PaymentStrategy {
    void pay(int amount);
}

具体策略

public class CreditCardPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Using Credit Card to pay: " + amount);
    }
}

public class PayPalPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Using PayPal to pay: " + amount);
    }
}

使用策略模式,我们可以轻松地切换支付方式,而无需修改其他代码。方法就是创建一个上下文对象,并将不同的策略对象注入到上下文中:

上下文

public class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(int amount) {
        paymentStrategy.pay(amount);
    }
}

而客户端代码只需要调用上下文对象的 checkout 方法,并根据需要设置不同的策略对象即可:

ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(new CreditCardPayment());
cart.checkout(100); // Using Credit Card to pay: 100

cart.setPaymentStrategy(new PayPalPayment());
cart.checkout(200); // Using PayPal to pay: 200

这样不仅能够轻松地切换支付方式,而且如果需要加入新的支付方式,只需创建新的策略对象并注入到上下文中,而不需要修改其他代码。

应用

posted @ 2024-12-08 15:42  Higurashi-kagome  阅读(25)  评论(0)    收藏  举报