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;
}

总结

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

相关推荐
zmd-zk2 分钟前
flink学习(2)——wordcount案例
大数据·开发语言·学习·flink
好奇的菜鸟6 分钟前
Go语言中的引用类型:指针与传递机制
开发语言·后端·golang
Alive~o.015 分钟前
Go语言进阶&依赖管理
开发语言·后端·golang
花海少爷17 分钟前
第十章 JavaScript的应用课后习题
开发语言·javascript·ecmascript
手握风云-18 分钟前
数据结构(Java版)第二期:包装类和泛型
java·开发语言·数据结构
喵叔哟37 分钟前
重构代码中引入外部方法和引入本地扩展的区别
java·开发语言·重构
尘浮生43 分钟前
Java项目实战II基于微信小程序的电影院买票选座系统(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven·intellij-idea
hopetomorrow1 小时前
学习路之PHP--使用GROUP BY 发生错误 SELECT list is not in GROUP BY clause .......... 解决
开发语言·学习·php
小牛itbull1 小时前
ReactPress vs VuePress vs WordPress
开发语言·javascript·reactpress
怀澈1221 小时前
高性能服务器模型之Reactor(单线程版本)
linux·服务器·网络·c++