Loading

[设计模式]策略模式

public interface Strategy {
    void doWork();
}
public class AliPay implements Strategy {
    @Override
    public void doWork() {
        System.out.println("正在使用支付宝支付");
    }
}
public class wxPay implements Strategy{
    @Override
    public void doWork() {
        System.out.println("正在使用微信支付");
    }
}
public class Context {
    private Strategy strategy;
    public void doWork(){
        strategy.doWork();
    }
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
}
public class Main {
    public static void main(String[] args) {
        Context context = new Context();

        AliPay aliPay = new AliPay();
        context.setStrategy(aliPay);
        context.doWork();

        wxPay wxPay = new wxPay();
        context.setStrategy(wxPay);
        context.doWork();
    }
}

给出另一个例子

下面是使用 策略模式 的 Java 代码示例,场景与之前的 Python 示例类似:一个电子商务平台的购物车系统,允许用户选择不同的支付方式(信用卡、PayPal、比特币)进行支付。

1. 策略接口

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

2. 具体策略类

(1) 信用卡支付策略

// 具体策略:信用卡支付
public class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;
    private String cardExpiry;
    private String cardCVC;

    public CreditCardPayment(String cardNumber, String cardExpiry, String cardCVC) {
        this.cardNumber = cardNumber;
        this.cardExpiry = cardExpiry;
        this.cardCVC = cardCVC;
    }

    @Override
    public void pay(double amount) {
        System.out.println("Paying " + amount + " using Credit Card ending with " + cardNumber.substring(cardNumber.length() - 4));
    }
}

(2) PayPal支付策略

// 具体策略:PayPal支付
public class PayPalPayment implements PaymentStrategy {
    private String email;

    public PayPalPayment(String email) {
        this.email = email;
    }

    @Override
    public void pay(double amount) {
        System.out.println("Paying " + amount + " using PayPal account " + email);
    }
}

(3) 比特币支付策略

// 具体策略:比特币支付
public class BitcoinPayment implements PaymentStrategy {
    private String walletAddress;

    public BitcoinPayment(String walletAddress) {
        this.walletAddress = walletAddress;
    }

    @Override
    public void pay(double amount) {
        System.out.println("Paying " + amount + " using Bitcoin wallet " + walletAddress);
    }
}

3. 上下文类

// 上下文类:购物车
import java.util.ArrayList;
import java.util.List;

public class ShoppingCart {
    private List<String> items;
    private double totalAmount;

    public ShoppingCart() {
        items = new ArrayList<>();
        totalAmount = 0.0;
    }

    // 添加商品到购物车
    public void addItem(String item, double price) {
        items.add(item);
        totalAmount += price;
    }

    // 使用支付策略进行支付
    public void pay(PaymentStrategy paymentStrategy) {
        paymentStrategy.pay(totalAmount);
    }
}

4. 测试策略模式

// 测试类
public class Main {
    public static void main(String[] args) {
        // 创建购物车对象
        ShoppingCart cart = new ShoppingCart();
        cart.addItem("Laptop", 1200);
        cart.addItem("Phone", 800);

        // 创建不同的支付策略
        PaymentStrategy creditCard = new CreditCardPayment("1234567812345678", "12/25", "123");
        PaymentStrategy paypal = new PayPalPayment("user@example.com");
        PaymentStrategy bitcoin = new BitcoinPayment("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa");

        // 使用不同的支付方式
        cart.pay(creditCard);  // 输出:Paying 2000.0 using Credit Card ending with 5678
        cart.pay(paypal);      // 输出:Paying 2000.0 using PayPal account user@example.com
        cart.pay(bitcoin);     // 输出:Paying 2000.0 using Bitcoin wallet 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
    }
}

代码解释:

  1. PaymentStrategy:这是一个接口,定义了一个支付行为 pay(double amount)。任何支付方式都必须实现这个接口。
  2. CreditCardPaymentPayPalPaymentBitcoinPayment:这些是策略模式的具体策略类,它们实现了不同的支付方式。
  3. ShoppingCart:这是上下文类,负责持有商品和总价。购物车不会直接依赖具体的支付实现,而是依赖于 PaymentStrategy 接口。这使得你可以随时更换支付方式,而不需要修改 ShoppingCart 的代码。
  4. Main:测试类,通过创建不同的支付方式并调用 ShoppingCartpay 方法,展示了策略模式的运行效果。

策略模式的好处:

  • 灵活性:可以轻松地增加新的支付方式而无需修改原有代码。
  • 遵循开闭原则:新策略的引入不需要对已有的上下文类做任何修改,系统可以很容易地扩展。
  • 简化代码:通过使用接口和抽象类,避免了大量的 if-elseswitch 语句。
posted @   Duancf  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示