「软件设计模式」装饰者模式(Decorator)

深入解析装饰者模式:动态扩展功能的艺术(C++实现)

一、模式思想与应用场景

1.1 模式定义

装饰者模式(Decorator Pattern)是一种结构型设计模式,它通过将对象放入包含行为的特殊封装对象中,动态地为原始对象添加新功能,比继承更灵活。

1.2 核心优势

  • 动态添加功能:运行时修改对象行为
  • 避免类爆炸:替代多层次的继承结构
  • 遵循开闭原则:扩展开放,修改关闭

1.3 典型应用场景

  • 需要动态/透明地给对象添加职责
  • 需要撤销已添加的功能
  • 不适合使用子类扩展的情况
  • 常见应用:
    • GUI组件装饰
    • 流处理(如Java I/O)
    • 游戏角色装备系统
    • 咖啡订单系统(本文示例)

二、模式结构与C++实现

2.1 UML类图解析

2.2 咖啡订单系统实现

基础组件接口
#include <iostream>
#include <memory>
#include <string>
// 抽象组件
class Beverage {
public:
    virtual ~Beverage() = default;
    virtual std::string getDescription() const = 0;
    virtual double cost() const = 0;
};

// 具体组件:浓缩咖啡
class Espresso : public Beverage {
public:
    std::string getDescription() const override {
        return "Espresso";
    }

    double cost() const override {
        return 1.99;
    }
};
装饰器基类
#include "component.h"
// 抽象装饰器
class CondimentDecorator : public Beverage {
public:
    explicit CondimentDecorator(std::unique_ptr<Be
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

There Is No Code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值