装饰器模式详解

8.9.6 装饰器模式

​ 装饰器模式是一种结构型模式,主要是给一个类添加更多功能;

示例代码:

c++ 复制代码
#include <iostream>
#include <string>

// 抽象基类:文本修饰器
class TextDecorator {
public:
    virtual std::string decorate(const std::string& text) const = 0;
};

// 具体修饰器:加粗修饰器
class BoldDecorator : public TextDecorator {
public:
    std::string decorate(const std::string& text) const override {
        return "<b>" + text + "</b>";
    }
};

// 具体修饰器:斜体修饰器
class ItalicDecorator : public TextDecorator {
public:
    std::string decorate(const std::string& text) const override {
        return "<i>" + text + "</i>";
    }
};

int main() {
    // 原始文本
    std::string text = "Hello, world!";

    // 创建修饰器对象
    TextDecorator* boldDecorator = new BoldDecorator();
    TextDecorator* italicDecorator = new ItalicDecorator();

    // 使用装饰器修饰文本
    std::string boldText = boldDecorator->decorate(text);
    std::string italicText = italicDecorator->decorate(text);

    // 显示修饰后的文本
    std::cout << "Bold Text: " << boldText << std::endl;
    std::cout << "Italic Text: " << italicText << std::endl;

    // 释放内存
    delete boldDecorator;
    delete italicDecorator;

    return 0;
}
相关推荐
Sakura_j_h_8 小时前
EasyEDA PCB 快速设计Skills
c++·python·github
ZhengEnCi8 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
算法·架构
程序喵大人8 小时前
【C++入门】内存模型与资源管理 - 09 shared_ptr 和 weak_ptr 解决共享,也带来代价
开发语言·c++·资源管理·智能指针·内存模型
秋天的怀念_David9 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Pniubi9 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
hhb_6189 小时前
大模型落地三重优化实战
人工智能·算法·机器学习
云和数据.ChenGuang9 小时前
光哥说Python RAG 系统需要哪些评估指标:从检索到生成的全链路评测指南
网络·人工智能·python·算法·langchain
jimy110 小时前
C++ 中的 `T&&`:右值引用与转发引用
开发语言·c++
2601_9707038311 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
心中有你021411 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法