策略模式(Strategy Pattern)是一種行為設(shè)計(jì)模式,它使你能在運(yùn)行時(shí)改變對(duì)象的行為
下面是一個(gè)簡單的示例,展示了如何在C++中實(shí)現(xiàn)策略模式:
#include<iostream>
#include<string>
// 策略接口
class Strategy {
public:
virtual ~Strategy() = default;
virtual void execute(const std::string& message) = 0;
};
// 具體策略A
class ConcreteStrategyA : public Strategy {
public:
void execute(const std::string& message) override {
std::cout << "Called ConcreteStrategyA with message: "<< message<< std::endl;
}
};
// 具體策略B
class ConcreteStrategyB : public Strategy {
public:
void execute(const std::string& message) override {
std::cout << "Called ConcreteStrategyB with message: "<< message<< std::endl;
}
};
class Context {
public:
Context(Strategy* strategy) : strategy_(strategy) {}
void set_strategy(Strategy* strategy) {
strategy_ = strategy;
}
void execute_strategy(const std::string& message) {
strategy_->execute(message);
}
private:
Strategy* strategy_;
};
int main() {
// 創(chuàng)建具體策略對(duì)象
ConcreteStrategyA strategy_a;
ConcreteStrategyB strategy_b;
// 創(chuàng)建上下文對(duì)象,并設(shè)置具體策略
Context context(&strategy_a);
// 執(zhí)行策略
context.execute_strategy("Hello, Strategy A!");
// 更改策略
context.set_strategy(&strategy_b);
// 再次執(zhí)行策略
context.execute_strategy("Hello, Strategy B!");
return 0;
}
這個(gè)示例展示了如何使用策略模式來動(dòng)態(tài)地改變對(duì)象的行為。你可以根據(jù)需要添加更多的具體策略類,并在上下文類中使用它們。