允许向一个现有的对象添加新的功能,而且不改变类的结构。

Demo

  1. """
  2. 装饰器模式
  3. """
  4. class Shape:
  5. def draw(self):
  6. raise NotImplementedError
  7. class Circle(Shape):
  8. def draw(self):
  9. print("this is circle")
  10. class ShapeDecorator:
  11. def __init__(self, shape: Shape):
  12. self.shape = shape
  13. def draw(self):
  14. self.shape.draw()
  15. class RedShapeDecorator(ShapeDecorator):
  16. def draw(self):
  17. super(RedShapeDecorator, self).draw()
  18. print('color is red')
  19. if __name__ == '__main__':
  20. c = Circle()
  21. c.draw()
  22. print("=" * 10)
  23. red_c = RedShapeDecorator(Circle())
  24. red_c.draw()