什么是装饰器模式
动态地给一个对象增加一些额外的职责,就扩展对象功能来说,装饰器模式比生成子类的方式更为灵活。
故事模拟
代码:
class Person:
"""人"""
def __init__(self, name):
self._name = name
def wear(self):
print('着装')
class Engineer(Person):
def __init__(self, name, skill):
super().__init__(name)
self.__skill = skill
def get_skill(self):
return self.__skill
def wear(self):
print('我是' + self.get_skill() + '工程师' + self._name, end=', ')
super().wear()
class Teacher(Person):
"""老师"""
def __init__(self, name, title):
super().__init__(name)
self.__title = title
def get_title(self):
return self.__title
def wear(self):
print('我是' + self._name + self.get_title(), end=', ')
super().wear()
class ClothingDecorator(Person):
"""服饰装饰器的基类"""
def __init__(self, person):
self._decorated = person
def wear(self):
self._decorated.wear()
self.decorated()
def decorated(self):
pass
class CasualPantDecorator(ClothingDecorator):
"""休闲裤装饰器"""
def __init__(self, person):
super().__init__(person)
def decorated(self):
print('一条卡其色休闲')
class BeltDecorator(ClothingDecorator):
"""腰带装饰器"""
def __init__(self, person):
super().__init__(person)
def decorated(self):
print('一条黑色腰带')
class LeatherShoesDecorator(ClothingDecorator):
"""皮鞋装饰器"""
def __init__(self, person):
super().__init__(person)
def decorated(self):
print('一双白色休闲鞋')
class KnittedDecorator(ClothingDecorator):
"""白色衬衫装饰器"""
def __init__(self, person):
super().__init__(person)
def decorated(self):
print('一双白色衬衫')
class GlassesDecorator(ClothingDecorator):
"""眼镜装饰器"""
def __init__(self, person):
super().__init__(person)
def decorated(self):
print('一副方形黑框眼镜')
def test_decorator():
tony = Engineer('Tony', '后台')
pant = CasualPantDecorator(tony)
belt = BeltDecorator(pant)
shoes = LeatherShoesDecorator(belt)
shirt = KnittedDecorator(shoes)
glasses = GlassesDecorator(shirt)
glasses.wear()
print()
decorator_teacher = GlassesDecorator(KnittedDecorator(LeatherShoesDecorator(BeltDecorator(Teacher('wells', '教授')))))
decorator_teacher.wear()
if __name__ == '__main__':
test_decorator()
装饰器模式设计思想
我们希望动态地给一个类增加额外的功能,而不动原有的代码,就是装饰器模式进行扩展。
Python中的装饰器
Python中函数的特殊功能
装饰器修饰函数
pass
装饰器修饰类
pass
模型说明
设计要点
1.可以灵活地给一个对象增加职责或者拓展共能。
2.可增加任意多个装饰器。
3.装饰的循序不同效果不同。
装饰器模式的优缺点
优点
1.使用装饰器模式来实现扩展比使用继承更灵活,它可以在不创建更多子类的情况下,将对象的功能进行扩展。
2.可以动态给一个对象附加更多的功能。
3.可以用不同装饰类进行多重装饰,装饰的顺序不同,可能产生不同的效果。
4.装饰类被装饰类可以独立扩展,不会相会耦合;装饰模式相当于继承的一个代替模式。
缺点
与继承相比,用装饰的方式扩展功能容易出错,排错也更加困难。对于多次装饰的对象,调试寻找错误时可能需要逐级排查,较为繁琐。
应用场景
1.大量独立扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长时。
2.需要动态增加或者撤销功能。
3.不能采用生成子类的方法进行扩充时,类的定义不能用生成的子类。装饰器模式的应用场景非常的广泛。如在实际项目开发中经常看到过滤器,便可使用装饰器模式的方式实现。