C++中的装饰器模式

目录

[装饰器模式(Decorator Pattern)](#装饰器模式(Decorator Pattern))

实际应用

图形对象装饰器

数据流装饰器

网络请求装饰器

总结


装饰器模式(Decorator Pattern)

装饰器模式是一种结构型设计模式,它允许你动态地向一个对象添加新的行为,而不改变其接口。这种模式通过将对象放入包含行为的特殊封装对象(装饰器)中来实现。装饰器模式提供了一种灵活的替代继承的方式来扩展对象的功能。

实际应用

图形对象装饰器

假设有一个图形对象,可能需要动态地添加边框、颜色等装饰。

cpp 复制代码
#include <iostream>
#include <memory>

// 图形接口
class Shape {
public:
    virtual ~Shape() = default;
    virtual void draw() const = 0;
};

// 具体实现:圆形
class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing Circle\n";
    }
};

// 具体实现:矩形
class Rectangle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing Rectangle\n";
    }
};

// 装饰器基类
class ShapeDecorator : public Shape {
protected:
    std::shared_ptr<Shape> decoratedShape;
public:
    ShapeDecorator(std::shared_ptr<Shape> shape) : decoratedShape(shape) {}
    virtual void draw() const override {
        decoratedShape->draw();
    }
};

// 具体装饰器:添加红色边框
class RedBorderDecorator : public ShapeDecorator {
public:
    RedBorderDecorator(std::shared_ptr<Shape> shape) : ShapeDecorator(shape) {}

    void draw() const override {
        decoratedShape->draw();
        setRedBorder();
    }

    void setRedBorder() const {
        std::cout << "Adding Red Border\n";
    }
};

// 具体装饰器:添加蓝色背景
class BlueBackgroundDecorator : public ShapeDecorator {
public:
    BlueBackgroundDecorator(std::shared_ptr<Shape> shape) : ShapeDecorator(shape) {}

    void draw() const override {
        decoratedShape->draw();
        setBlueBackground();
    }

    void setBlueBackground() const {
        std::cout << "Adding Blue Background\n";
    }
};

int main() {
    std::shared_ptr<Shape> circle = std::make_shared<Circle>();
    std::shared_ptr<Shape> redCircle = std::make_shared<RedBorderDecorator>(circle);
    std::shared_ptr<Shape> blueRedCircle = std::make_shared<BlueBackgroundDecorator>(redCircle);

    std::cout << "Circle with normal border:\n";
    circle->draw();

    std::cout << "\nCircle with red border:\n";
    redCircle->draw();

    std::cout << "\nCircle with red border and blue background:\n";
    blueRedCircle->draw();

    return 0;
}

数据流装饰器

假设有一个数据流,可以动态地向数据流添加不同的处理,如加密、压缩等。

cpp 复制代码
#include <iostream>
#include <memory>
#include <string>

// 数据流接口
class DataStream {
public:
    virtual ~DataStream() = default;
    virtual void write(const std::string& data) = 0;
};

// 具体实现:文件数据流
class FileDataStream : public DataStream {
public:
    void write(const std::string& data) override {
        std::cout << "Writing data to file: " << data << "\n";
    }
};

// 装饰器基类
class DataStreamDecorator : public DataStream {
protected:
    std::shared_ptr<DataStream> wrappee;
public:
    DataStreamDecorator(std::shared_ptr<DataStream> stream) : wrappee(stream) {}

    void write(const std::string& data) override {
        wrappee->write(data);
    }
};

// 具体装饰器:加密数据流
class EncryptedDataStream : public DataStreamDecorator {
public:
    EncryptedDataStream(std::shared_ptr<DataStream> stream) : DataStreamDecorator(stream) {}

    void write(const std::string& data) override {
        std::string encryptedData = encrypt(data);
        DataStreamDecorator::write(encryptedData);
    }

    std::string encrypt(const std::string& data) {
        return "Encrypted(" + data + ")";
    }
};

// 具体装饰器:压缩数据流
class CompressedDataStream : public DataStreamDecorator {
public:
    CompressedDataStream(std::shared_ptr<DataStream> stream) : DataStreamDecorator(stream) {}

    void write(const std::string& data) override {
        std::string compressedData = compress(data);
        DataStreamDecorator::write(compressedData);
    }

    std::string compress(const std::string& data) {
        return "Compressed(" + data + ")";
    }
};

int main() {
    std::shared_ptr<DataStream> fileStream = std::make_shared<FileDataStream>();
    std::shared_ptr<DataStream> encryptedStream = std::make_shared<EncryptedDataStream>(fileStream);
    std::shared_ptr<DataStream> compressedEncryptedStream = std::make_shared<CompressedDataStream>(encryptedStream);

    std::cout << "Writing plain data to file:\n";
    fileStream->write("Hello World");

    std::cout << "\nWriting encrypted data to file:\n";
    encryptedStream->write("Hello World");

    std::cout << "\nWriting compressed and encrypted data to file:\n";
    compressedEncryptedStream->write("Hello World");

    return 0;
}

网络请求装饰器

假设有一个网络请求对象,可以动态地添加日志记录、重试等功能。

cpp 复制代码
#include <iostream>
#include <memory>
#include <string>

// 网络请求接口
class NetworkRequest {
public:
    virtual ~NetworkRequest() = default;
    virtual void execute() const = 0;
};

// 具体实现:基础网络请求
class BasicNetworkRequest : public NetworkRequest {
public:
    void execute() const override {
        std::cout << "Executing basic network request\n";
    }
};

// 装饰器基类
class NetworkRequestDecorator : public NetworkRequest {
protected:
    std::shared_ptr<NetworkRequest> wrappee;
public:
    NetworkRequestDecorator(std::shared_ptr<NetworkRequest> request) : wrappee(request) {}

    void execute() const override {
        wrappee->execute();
    }
};

// 具体装饰器:日志记录
class LoggingNetworkRequest : public NetworkRequestDecorator {
public:
    LoggingNetworkRequest(std::shared_ptr<NetworkRequest> request) : NetworkRequestDecorator(request) {}

    void execute() const override {
        log();
        NetworkRequestDecorator::execute();
    }

    void log() const {
        std::cout << "Logging network request\n";
    }
};

// 具体装饰器:重试机制
class RetryNetworkRequest : public NetworkRequestDecorator {
private:
    int retries;
public:
    RetryNetworkRequest(std::shared_ptr<NetworkRequest> request, int retries) : NetworkRequestDecorator(request), retries(retries) {}

    void execute() const override {
        for (int i = 0; i < retries; ++i) {
            try {
                NetworkRequestDecorator::execute();
                return;
            } catch (...) {
                std::cout << "Retry " << i + 1 << " failed\n";
            }
        }
        std::cout << "All retries failed\n";
    }
};

int main() {
    std::shared_ptr<NetworkRequest> basicRequest = std::make_shared<BasicNetworkRequest>();
    std::shared_ptr<NetworkRequest> loggedRequest = std::make_shared<LoggingNetworkRequest>(basicRequest);
    std::shared_ptr<NetworkRequest> retriedLoggedRequest = std::make_shared<RetryNetworkRequest>(loggedRequest, 3);

    std::cout << "Executing basic request:\n";
    basicRequest->execute();

    std::cout << "\nExecuting logged request:\n";
    loggedRequest->execute();

    std::cout << "\nExecuting retried and logged request:\n";
    retriedLoggedRequest->execute();

    return 0;
}

总结

装饰器模式可以使对象在运行时动态地添加新的行为而不改变其接口。这使得我们可以灵活地扩展对象的功能,而不需要修改已有的代码。

相关推荐
懒大王爱吃狼37 分钟前
Python教程:python枚举类定义和使用
开发语言·前端·javascript·python·python基础·python编程·python书籍
秃头佛爷2 小时前
Python学习大纲总结及注意事项
开发语言·python·学习
待磨的钝刨2 小时前
【格式化查看JSON文件】coco的json文件内容都在一行如何按照json格式查看
开发语言·javascript·json
XiaoLeisj4 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
励志成为嵌入式工程师5 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
捕鲸叉5 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer5 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法
Peter_chq5 小时前
【操作系统】基于环形队列的生产消费模型
linux·c语言·开发语言·c++·后端
记录成长java7 小时前
ServletContext,Cookie,HttpSession的使用
java·开发语言·servlet
前端青山7 小时前
Node.js-增强 API 安全性和性能优化
开发语言·前端·javascript·性能优化·前端框架·node.js