装饰器模式详解

8.9.6 装饰器模式

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

示例代码:

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

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值