设计模式_策略模式

策略模式(Strategy Pattern)详解

策略模式是一种行为设计模式,它定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户端。

核心概念

  1. 策略(Strategy):定义所有支持的算法的公共接口
  2. 具体策略(Concrete Strategy):实现策略接口的具体算法类
  3. 上下文(Context):持有一个策略对象的引用,通过策略接口与具体策略交互

模式结构

Context
|__ strategy: Strategy
|__ contextInterface()

Strategy (Interface/Abstract Class)
|__ algorithmInterface()

ConcreteStrategyA
|__ algorithmInterface()

ConcreteStrategyB
|__ algorithmInterface()

实现示例(C++)

#include <iostream>
#include <memory>

// 策略接口
class PaymentStrategy {
public:
    virtual ~PaymentStrategy() = default;
    virtual void pay(double amount) = 0;
};

// 具体策略 - 信用卡支付
class CreditCardPayment : public PaymentStrategy {
public:
    void pay(double amount) override {
        std::cout << "使用信用卡支付: " << amount << "元" << std::endl;
    }
};

// 具体策略 - 支付宝支付
class AlipayPayment : public PaymentStrategy {
public:
    void pay(double amount) override {
        std::cout << "使用支付宝支付: " << amount << "元" << std::endl;
    }
};

// 具体策略 - 微信支付
class WechatPayment : public PaymentStrategy {
public:
    void pay(double amount) override {
        std::cout << "使用微信支付: " << amount << "元" << std::endl;
    }
};

// 上下文
class PaymentContext {
public:
    explicit PaymentContext(std::unique_ptr<PaymentStrategy> strategy)
        : strategy_(std::move(strategy)) {}
    
    void setStrategy(std::unique_ptr<PaymentStrategy> strategy) {
        strategy_ = std::move(strategy);
    }
    
    void executePayment(double amount) {
        strategy_->pay(amount);
    }

private:
    std::unique_ptr<PaymentStrategy> strategy_;
};

// 客户端代码
int main() {
    PaymentContext context(std::make_unique<CreditCardPayment>());
    
    // 使用信用卡支付
    context.executePayment(100.0);
    
    // 切换到支付宝支付
    context.setStrategy(std::make_unique<AlipayPayment>());
    context.executePayment(200.0);
    
    // 切换到微信支付
    context.setStrategy(std::make_unique<WechatPayment>());
    context.executePayment(300.0);
    
    return 0;
}

策略模式优点

  1. 开闭原则:无需修改上下文即可引入新策略
  2. 消除条件语句:替代复杂的条件选择逻辑
  3. 算法复用:不同上下文可以共享策略对象
  4. 运行时切换:可以在运行时切换算法

适用场景

  1. 系统需要在多种算法中选择一种时
  2. 需要避免暴露复杂算法具体实现时
  3. 有多个相似类仅在行为上有差异时
  4. 需要动态切换算法时

现实生活例子:导航系统

导航系统可以使用策略模式来切换不同的路径计算算法:

  • 最短路径策略
  • 最快路径策略
  • 避开高速策略
  • 风景路线策略
  • 旅游出行选择方式

用户可以根据需要选择不同的导航策略,而导航系统本身的结构不需要改变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值