【C++】【设计模式】装饰器模式(Decorator Pattern)
定义
- 结构型模式
- 旨在通过关联机制将一个类的对象动态地嵌入另一个对象中,另一个对象调用嵌入对象的行为便可实现扩展自己的功能的效果
结构
- 抽象构建
- 具体构建
- 抽象装饰类
- 具体装饰类
UML类![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/9d6bbb1ce4fc4ba7ac1f5e3d98fa4eaf.png)
图
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;
}
分析总结
- 一种功能叠加的思想,针对于方法和非整个类的关系可以减少耦合
- 动态添加额外功能,比使用子类更加灵活,符合开闭原则
- 代码结构复杂,排查问题难度增加
- 可能要额外管理装饰顺序