C++ 设计模式之策略模式

策略模式允许你定义一系列算法,将每个算法封装起来,并使它们可以互换。以下是一个简单的 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;
}
相关推荐
小黄人软件6 分钟前
C++读写编辑CSV文件示例源码 用于数据导入导出,比Excel好使
开发语言·c++·excel
希望永不加班8 分钟前
枚举进阶用法:超越常量的设计模式应用
设计模式
郭涤生13 分钟前
C++各个版本的性能和安全性总结
开发语言·c++
wljy11 小时前
二、静态库的制作和使用
linux·c语言·开发语言·c++
道剑剑非道2 小时前
FFmpeg 6.0 实战:用 C++ 封装摄像头采集与 RTSP 推流
开发语言·c++·ffmpeg
光电笑映2 小时前
从环境变量到进程虚拟地址空间——Linux 内存管理的底层脉络
linux·服务器·c++·c
summer__77772 小时前
设计模式知识点总结
设计模式
青山师2 小时前
动态代理深度解析:JDK与CGLIB底层实现与实战
java·设计模式·面试·动态代理·java面试·cglib
sparEE3 小时前
c++字符串和自定义字面量
开发语言·c++
蜡笔小马4 小时前
03.C++设计模式-原型模式
c++·设计模式·原型模式