设计模式-策略模式

文章展示了如何使用C++实现策略模式,定义了一个策略接口Strategy和三个实现该接口的具体策略类ConcreteStrategyA、B、C。Context类作为上下文,持有Strategy对象并调用其execute方法执行不同算法。在main函数中,通过改变Context的策略对象,实现了算法的动态切换。
摘要由CSDN通过智能技术生成

策略模式是一种行为型设计模式,它定义了一系列算法,将每个算法都封装起来,并使它们可以互换。
下面是一个使用C++实现策略模式的示例代码:

#include <iostream>
#include <string>
// 定义一个策略接口
class Strategy {
public:
    virtual ~Strategy() {}
    virtual std::string execute() = 0;
};
// 实现策略接口的具体类
class ConcreteStrategyA : public Strategy {
public:
    std::string execute() override {
        return "ConcreteStrategyA";
    }
};
class ConcreteStrategyB : public Strategy {
public:
    std::string execute() override {
        return "ConcreteStrategyB";
    }
};
class ConcreteStrategyC : public Strategy {
public:
    std::string execute() override {
        return "ConcreteStrategyC";
    }
};
// 定义一个上下文类
class Context {
public:
    Context(Strategy* strategy) : strategy_(strategy) {}
    void set_strategy(Strategy* strategy) {
        strategy_ = strategy;
    }
    std::string execute_strategy() {
        return strategy_->execute();
    }
private:
    Strategy* strategy_;
};
// 使用示例
int main() {
    ConcreteStrategyA strategy_a;
    ConcreteStrategyB strategy_b;
    ConcreteStrategyC strategy_c;
    Context context(&strategy_a);
    std::cout << context.execute_strategy() << std::endl;  // 输出: ConcreteStrategyA
    context.set_strategy(&strategy_b);
    std::cout << context.execute_strategy() << std::endl;  // 输出: ConcreteStrategyB
    context.set_strategy(&strategy_c);
    std::cout << context.execute_strategy() << std::endl;  // 输出: ConcreteStrategyC
    return 0;
}

在上面的示例中,我们定义了一个策略接口 Strategy,以及三个具体的策略类 ConcreteStrategyAConcreteStrategyB ConcreteStrategyC,它们都实现了 Strategy 接口中的execute方法。
然后我们定义了一个上下文类 Context,它可以接受一个 Strategy 对象作为参数,并在内部保存该对象。Context 类中有一个 execute_strategy 方法,它调用当前保存的策略对象的 execute 方法来执行具体的算法。
main 函数中,我们可以创建不同的策略对象,并将它们传递给 Context 类的实例。通过调用 execute_strategy 方法,我们可以看到Context类执行的具体算法不同,这就是策略模式的作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值