什么是装饰器模式

动态地给一个对象增加一些额外的职责,就扩展对象功能来说,装饰器模式比生成子类的方式更为灵活。

故事模拟

代码:

  1. class Person:
  2. """人"""
  3. def __init__(self, name):
  4. self._name = name
  5. def wear(self):
  6. print('着装')
  7. class Engineer(Person):
  8. def __init__(self, name, skill):
  9. super().__init__(name)
  10. self.__skill = skill
  11. def get_skill(self):
  12. return self.__skill
  13. def wear(self):
  14. print('我是' + self.get_skill() + '工程师' + self._name, end=', ')
  15. super().wear()
  16. class Teacher(Person):
  17. """老师"""
  18. def __init__(self, name, title):
  19. super().__init__(name)
  20. self.__title = title
  21. def get_title(self):
  22. return self.__title
  23. def wear(self):
  24. print('我是' + self._name + self.get_title(), end=', ')
  25. super().wear()
  26. class ClothingDecorator(Person):
  27. """服饰装饰器的基类"""
  28. def __init__(self, person):
  29. self._decorated = person
  30. def wear(self):
  31. self._decorated.wear()
  32. self.decorated()
  33. def decorated(self):
  34. pass
  35. class CasualPantDecorator(ClothingDecorator):
  36. """休闲裤装饰器"""
  37. def __init__(self, person):
  38. super().__init__(person)
  39. def decorated(self):
  40. print('一条卡其色休闲')
  41. class BeltDecorator(ClothingDecorator):
  42. """腰带装饰器"""
  43. def __init__(self, person):
  44. super().__init__(person)
  45. def decorated(self):
  46. print('一条黑色腰带')
  47. class LeatherShoesDecorator(ClothingDecorator):
  48. """皮鞋装饰器"""
  49. def __init__(self, person):
  50. super().__init__(person)
  51. def decorated(self):
  52. print('一双白色休闲鞋')
  53. class KnittedDecorator(ClothingDecorator):
  54. """白色衬衫装饰器"""
  55. def __init__(self, person):
  56. super().__init__(person)
  57. def decorated(self):
  58. print('一双白色衬衫')
  59. class GlassesDecorator(ClothingDecorator):
  60. """眼镜装饰器"""
  61. def __init__(self, person):
  62. super().__init__(person)
  63. def decorated(self):
  64. print('一副方形黑框眼镜')
  65. def test_decorator():
  66. tony = Engineer('Tony', '后台')
  67. pant = CasualPantDecorator(tony)
  68. belt = BeltDecorator(pant)
  69. shoes = LeatherShoesDecorator(belt)
  70. shirt = KnittedDecorator(shoes)
  71. glasses = GlassesDecorator(shirt)
  72. glasses.wear()
  73. print()
  74. decorator_teacher = GlassesDecorator(KnittedDecorator(LeatherShoesDecorator(BeltDecorator(Teacher('wells', '教授')))))
  75. decorator_teacher.wear()
  76. if __name__ == '__main__':
  77. test_decorator()

装饰器模式设计思想

我们希望动态地给一个类增加额外的功能,而不动原有的代码,就是装饰器模式进行扩展。

Python中的装饰器

Python中函数的特殊功能

装饰器修饰函数

pass

装饰器修饰类

pass

模型说明

设计要点

1.可以灵活地给一个对象增加职责或者拓展共能。
2.可增加任意多个装饰器。
3.装饰的循序不同效果不同。

装饰器模式的优缺点

优点

1.使用装饰器模式来实现扩展比使用继承更灵活,它可以在不创建更多子类的情况下,将对象的功能进行扩展。
2.可以动态给一个对象附加更多的功能。
3.可以用不同装饰类进行多重装饰,装饰的顺序不同,可能产生不同的效果。
4.装饰类被装饰类可以独立扩展,不会相会耦合;装饰模式相当于继承的一个代替模式。

缺点

与继承相比,用装饰的方式扩展功能容易出错,排错也更加困难。对于多次装饰的对象,调试寻找错误时可能需要逐级排查,较为繁琐。

应用场景

1.大量独立扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长时。
2.需要动态增加或者撤销功能。
3.不能采用生成子类的方法进行扩充时,类的定义不能用生成的子类。装饰器模式的应用场景非常的广泛。如在实际项目开发中经常看到过滤器,便可使用装饰器模式的方式实现。