策略模式允许你定义一系列算法,将每个算法封装起来,并使它们可以互换。以下是一个简单的 C++ 策略模式的示例,假设我们有一个图形绘制类,可以选择不同的绘制策略:
cpp
#include <iostream>
// 抽象策略类
class DrawingStrategy {
public:
virtual void draw() = 0;
virtual ~DrawingStrategy() {}
};
// 具体策略类A
class DrawCircle : public DrawingStrategy {
public:
void draw() override {
std::cout << "Draw a circle." << std::endl;
}
};
// 具体策略类B
class DrawRectangle : public DrawingStrategy {
public:
void draw() override {
std::cout << "Draw a rectangle." << std::endl;
}
};
// 上下文类,用于执行策略
class DrawingContext {
private:
DrawingStrategy* strategy;
public:
DrawingContext(DrawingStrategy* initialStrategy) : strategy(initialStrategy) {}
void setStrategy(DrawingStrategy* newStrategy) {
strategy = newStrategy;
}
void executeDraw() {
strategy->draw();
}
};
int main() {
// 创建具体策略对象
DrawCircle circleStrategy;
DrawRectangle rectangleStrategy;
// 创建上下文对象,并设置初始策略
DrawingContext context(&circleStrategy);
// 执行绘制操作
context.executeDraw();
// 更换策略
context.setStrategy(&rectangleStrategy);
// 再次执行绘制操作
context.executeDraw();
return 0;
}