大话设计模式之装饰模式

装饰模式(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;
}
相关推荐
__万波__9 小时前
二十三种设计模式(二)--工厂方法模式
java·设计模式·工厂方法模式
前端老宋Running11 小时前
React 的“时光胶囊”:useRef 才是那个打破“闭包陷阱”的救世主
前端·react.js·设计模式
Tzarevich12 小时前
从字面量到原型链:JavaScript 面向对象的完整进化史
javascript·设计模式
繁华似锦respect16 小时前
C++ 设计模式之工厂模式详细介绍
java·linux·c++·网络协议·设计模式
想要成为祖国的花朵16 小时前
基于多设计模式的抽奖系统__测试报告
java·selenium·测试工具·jmeter·设计模式·测试用例·安全性测试
重铸码农荣光19 小时前
JavaScript 面向对象编程:从字面量到原型继承的深度探索
前端·javascript·设计模式
L***d67021 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
未可知77721 小时前
软件设计师(下午题2)、UML与设计模式
算法·设计模式·职场和发展·uml
繁华似锦respect21 小时前
C++ 设计模式之单例模式详细介绍
服务器·开发语言·c++·windows·visualstudio·单例模式·设计模式
xunyan623421 小时前
面向对象(下)-设计模式与单例设计模式
java·单例模式·设计模式