策略模式是一种行为型设计模式,它定义了一系列算法,将每个算法都封装起来,并使它们可以互换。
下面是一个使用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
,以及三个具体的策略类 ConcreteStrategyA
、ConcreteStrategyB
和 ConcreteStrategyC
,它们都实现了 Strategy
接口中的execute
方法。
然后我们定义了一个上下文类 Context
,它可以接受一个 Strategy
对象作为参数,并在内部保存该对象。Context
类中有一个 execute_strategy
方法,它调用当前保存的策略对象的 execute
方法来执行具体的算法。
在 main
函数中,我们可以创建不同的策略对象,并将它们传递给 Context
类的实例。通过调用 execute_strategy
方法,我们可以看到Context
类执行的具体算法不同,这就是策略模式的作用。