大话设计模式之装饰模式

装饰模式(Decorator Pattern)是一种结构型设计模式,它允许向现有对象动态地添加新功能,同时又不改变其结构。装饰模式通过将对象放入包装器中来实现,在包装器中可以动态地添加功能。

在装饰模式中,通常会有四个角色:

  1. Component(组件):定义一个对象接口,可以动态地给这些对象添加职责。
  2. ConcreteComponent(具体组件):实现Component接口,并定义需要被装饰的类。
  3. Decorator(装饰器):持有一个Component对象的引用,并定义一个与Component接口一致的接口。
  4. ConcreteDecorator(具体装饰器):扩展Decorator类,覆盖其中的方法,以添加新的功能。
cpp 复制代码
#include <iostream>

// Component(组件)
class Coffee {
public:
    virtual void makeCoffee() = 0;
};

// ConcreteComponent(具体组件)
class SimpleCoffee : public Coffee {
public:
    void makeCoffee() override {
        std::cout << "Making simple coffee" << std::endl;
    }
};

// Decorator(装饰器)
class CoffeeDecorator : public Coffee {
protected:
    Coffee* coffee;

public:
    CoffeeDecorator(Coffee* coffee) : coffee(coffee) {}

    void makeCoffee() override {
        if (coffee) {
            coffee->makeCoffee();
        }
    }
};

// ConcreteDecorator(具体装饰器)
class MilkDecorator : public CoffeeDecorator {
public:
    MilkDecorator(Coffee* coffee) : CoffeeDecorator(coffee) {}

    void makeCoffee() override {
        if (coffee) {
            coffee->makeCoffee();
            addMilk();
        }
    }

    void addMilk() {
        std::cout << "Adding milk" << std::endl;
    }
};

// ConcreteDecorator(具体装饰器)
class SugarDecorator : public CoffeeDecorator {
public:
    SugarDecorator(Coffee* coffee) : CoffeeDecorator(coffee) {}

    void makeCoffee() override {
        if (coffee) {
            coffee->makeCoffee();
            addSugar();
        }
    }

    void addSugar() {
        std::cout << "Adding sugar" << std::endl;
    }
};

int main(int argc, char *argv[])
{
    // 创建一个简单的咖啡对象
    Coffee* simpleCoffee = new SimpleCoffee();

    // 使用装饰器为咖啡添加牛奶
    Coffee* milkCoffee = new MilkDecorator(simpleCoffee);

    // 制作带牛奶的咖啡
    milkCoffee->makeCoffee();

    // 使用装饰器为牛奶咖啡添加糖
    Coffee* milkSugarCoffee = new SugarDecorator(milkCoffee);
    milkSugarCoffee->makeCoffee();

    delete simpleCoffee;
    delete milkCoffee;
    delete milkSugarCoffee;

    return 0;
}
相关推荐
是2的10次方啊6 小时前
设计模式与生活①:你的脸,为什么不能有第二个?
设计模式
高晶8 小时前
ARM 嵌入式 Linux 命令系统 BusyBox 实战指南
linux·设计模式·程序员
高晶8 小时前
语音合成与变声技术十大业务场景落地实战:从电商直播到规模化生产
设计模式·程序员
博风11 小时前
19、设计模式应用举例:桥接模式:制作电视节目
设计模式·桥接模式
知守观11 小时前
从 4 套 PDF 库的混战,聊聊老项目的依赖管理与“静默失败”
java·后端·设计模式
geovindu1 天前
rust: Mediator Pattern
开发语言·后端·设计模式·rust·中介者模式·行为模式
SENKS_DIGITAL1 天前
金属加工遇上数字化:通快展厅里的工业蜕变-森克思科技
科技·设计模式·展厅设计·展馆设计·科技展厅设计·展览设计·企业展厅设计
flower9803231 天前
C++消息总线软件开发框架AI重构版
c++·设计模式·架构
zzu123zsw3 天前
业务拆分后的治理深水区:解构企业级微服务六大核心设计模式与高可用落真实践
微服务·设计模式·架构·高可用·微服务架构设计
牧瀬クリスだ3 天前
观察者模式:一个对象变化,一群对象自动响应
java·观察者模式·设计模式