跳转至

装饰器模式

功能:装饰器模式(Decorator Pattern)允许动态扩展(添加或移除)对象新的功能,同时又不改变其结构。 Decorator Pattern

  • 示例
// decoratorFrame.cpp (based on https://en.wikipedia.org/wiki/Decorator_pattern)

#include <iostream>
#include <string>

struct Shape{
  virtual std::string str() const = 0;
};

class Circle : public Shape{
  float radius = 10.0f;

public:
  std::string str() const override{
    return std::string("A circle of radius ") + std::to_string(radius);
  }
};

class ColoredShape : public Shape{
  std::string color;
  Shape& shape;
public:
  ColoredShape(std::string c, Shape& s): color{c}, shape{s} {}
  std::string str() const override{
    return shape.str() + std::string(" which is coloured ") + color;
  }
};

class FramedShape : public Shape{
  Shape& shape;
public:
  FramedShape(Shape& s): shape{s} {}
  std::string str() const override{
    return shape.str() + std::string(" and has a frame");
  }
};

int main(){

  Circle circle;
  ColoredShape coloredShape("red", circle);    // (1)
  FramedShape framedShape1(circle);            // (2)
  FramedShape framedShape2(coloredShape);      // (3)

  std::cout << circle.str() << '\n';
  std::cout << coloredShape.str() << '\n';
  std::cout << framedShape1.str() << '\n';
  std::cout << framedShape2.str() << '\n';

}
  • 可能的输出
A circle of radius 10.000000
A circle of radius 10.000000 which is coloured red
A circle of radius 10.000000 and has a frame
A circle of radius 10.000000 which is coloured red and has a frame

1 装饰器模式和组合模式比较

  • 装饰器模式和组合模式很相似,但功能侧重点不同,装饰器是为了给对象扩展一个功能,而组合模式是为了构成树形结构
  • 装饰器模式有一个 1 对 1 的关系,而组合模式有一个 1 对 n 的关系。这样就使组合模式可以形成树形结构,而装饰器只能是链式结构