【C++】【设计模式】装饰器模式

【C++】【设计模式】装饰器模式(Decorator Pattern)

定义

  • 结构型模式
  • 旨在通过关联机制将一个类的对象动态地嵌入另一个对象中,另一个对象调用嵌入对象的行为便可实现扩展自己的功能的效果

结构

  • 抽象构建
  • 具体构建
  • 抽象装饰类
  • 具体装饰类

UML类在这里插入图片描述

Demo源码

#include <iostream>
#include <memory>
#include <string>

// Abstract base class: Shape
class Shape {
public:
    virtual void draw() const = 0;
    virtual ~Shape() {}
};

// Concrete class: Circle
class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Circle\n";
    }
};

// Concrete class: Rectangle
class Rectangle : public Shape {
public:
    void draw() const override {
        std::cout << "Rectangle\n";
    }
};

// Abstract decorator class
class ShapeDecorator : public Shape {
public:
    ShapeDecorator(std::unique_ptr<Shape>&& shape) : shape_(std::move(shape)) {}
    void draw() const override { shape_->draw(); }

protected:
    std::unique_ptr<Shape> shape_;
};

// Concrete decorator class: Border
class BorderDecorator : public ShapeDecorator {
public:
    BorderDecorator(std::unique_ptr<Shape>&& shape) : ShapeDecorator(std::move(shape)) {}
    void draw() const override {
        std::cout << "Border ";
        shape_->draw();
    }
};

// Concrete decorator class: Fill
class FillDecorator : public ShapeDecorator {
public:
    FillDecorator(std::unique_ptr<Shape>&& shape) : ShapeDecorator(std::move(shape)) {}
    void draw() const override {
        std::cout << "Fill ";
        shape_->draw();
    }
};

// Client code
int main() {
    // Create a Circle
    std::unique_ptr<Shape> circle = std::make_unique<Circle>();

    // Create a Circle with a Border
    std::unique_ptr<Shape> circleWithBorder = std::make_unique<BorderDecorator>(std::make_unique<Circle>());

    // Create a Rectangle with a Border and Fill
    std::unique_ptr<Shape> rectangleWithBorderAndFill = std::make_unique<FillDecorator>(
        std::make_unique<BorderDecorator>(std::make_unique<Rectangle>()));

    // Output results
    std::cout << "Circle: ";
    circle->draw();
    std::cout << "Circle with border: ";
    circleWithBorder->draw();
    std::cout << "Rectangle with border and fill: ";
    rectangleWithBorderAndFill->draw();

    return 0;
}

分析总结

  • 一种功能叠加的思想,针对于方法和非整个类的关系可以减少耦合
  • 动态添加额外功能,比使用子类更加灵活,符合开闭原则
  • 代码结构复杂,排查问题难度增加
  • 可能要额外管理装饰顺序
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值