欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > 设计模式之策略模式

设计模式之策略模式

2024/10/25 6:25:54 来源:https://blog.csdn.net/qq_39437730/article/details/142547104  浏览:    关键词:设计模式之策略模式

策略模式(Strategy Pattern)是一种行为型设计模式,旨在定义一系列算法,将每个算法封装起来,并使它们可以互换。该模式让算法的变化独立于使用算法的客户。这种设计模式在需要选择多种算法中的一种时非常有用,尤其是在不想让客户端代码直接依赖于具体实现的情况下。

1. 策略模式的结构

策略模式通常由以下几个部分组成:

  • 上下文(Context):持有一个策略类的引用,负责在运行时调用策略的行为。
  • 策略接口(Strategy):定义所有支持的算法或行为的公共接口。
  • 具体策略(Concrete Strategy):实现策略接口的具体算法。

2. 策略模式的优点

  • 灵活性:可以在运行时选择算法,易于切换和扩展。
  • 开放/封闭原则:可以添加新的策略而无需修改上下文代码,符合软件设计中的开放/封闭原则。
  • 避免大量条件语句:可以将不同的行为封装在策略类中,而不是在上下文中使用条件语句进行选择。

3. 策略模式的缺点

  • 增加类的数量:每个策略都需要一个类,因此可能会导致类数量增加。
  • 客户端必须了解不同的策略:客户端代码需要了解可用的策略,可能会增加复杂性。

4. 策略模式的示例

下面是一个使用策略模式的简单示例,展示如何实现不同的支付方式。

示例代码:支付策略
#include <iostream>
#include <memory>// 策略接口
class PaymentStrategy {
public:virtual void pay(int amount) = 0; // 纯虚函数virtual ~PaymentStrategy() = default; // 虚析构函数
};// 具体策略:信用卡支付
class CreditCardPayment : public PaymentStrategy {
public:void pay(int amount) override {std::cout << "Paid " << amount << " using Credit Card." << std::endl;}
};// 具体策略:PayPal支付
class PayPalPayment : public PaymentStrategy {
public:void pay(int amount) override {std::cout << "Paid " << amount << " using PayPal." << std::endl;}
};// 上下文类
class ShoppingCart {
public:void setPaymentStrategy(std::unique_ptr<PaymentStrategy> strategy) {paymentStrategy = std::move(strategy);}void checkout(int amount) {if (paymentStrategy) {paymentStrategy->pay(amount);} else {std::cout << "No payment strategy set." << std::endl;}}private:std::unique_ptr<PaymentStrategy> paymentStrategy;
};int main() {ShoppingCart cart;// 使用信用卡支付cart.setPaymentStrategy(std::make_unique<CreditCardPayment>());cart.checkout(100);// 使用PayPal支付cart.setPaymentStrategy(std::make_unique<PayPalPayment>());cart.checkout(200);return 0;
}

5. 示例解释

  • 策略接口:
    • PaymentStrategy 定义了一个纯虚函数 pay,不同的支付策略需要实现这个接口。
  • 具体策略:
    • CreditCardPaymentPayPalPayment 是具体策略类,分别实现了使用信用卡和 PayPal 进行支付的具体逻辑。
  • 上下文:
    • ShoppingCart 类持有一个 PaymentStrategy 的指针,通过 setPaymentStrategy 方法可以动态设置不同的支付策略。
    • checkout 方法调用当前设置的支付策略的 pay 方法,完成支付操作。

6. 总结

策略模式提供了一种灵活的方式来选择和改变算法。通过将算法封装在策略类中,可以很容易地扩展和维护代码。策略模式特别适合需要多种行为的场合,如支付、排序、过滤等场景。使用策略模式,可以使得代码更加清晰、易于理解和维护。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com