装饰模式简介
所谓的装饰模式,就是为已有的功能动态地添加更多功能的一种方式。跟策略模式类似,装饰模式中新添加的功能同样具有“可插拔性”。不同的是,在装饰模式中,可以同时添加不止一个新功能。
在装饰模式中,新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。它把每个想要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地,按顺序地使用装饰功能包装对象。
优点:
-
- 将类中的装饰功能从类中搬移去除,简化原有的类。
- 有效地将类的核心责任和装饰功能区分开
案例分析
题目:模拟一个人穿衣过程。
人的衣服,不就是对人的装饰吗,很贴合主题。代码如下:
#!/usr/bin/env python
# _*_ coding utf-8 _*_
#Author: aaron
from abc import ABCMeta, abstractmethod
class Person(object):
def __init__(self, name):
self.name = name
def decorator(self, component):
self.component = component
def show(self):
print('%s开始穿衣' % self.name)
self.component.show()
class Finery():
def __init__(self):
self.component = None
def decorator(self, component):
self.component = component
__metaclass__ = ABCMeta
@abstractmethod
def show(self):
if self.component:
self.component.show()
class TShirt(Finery):
def show(self):
Finery.show(self)
print ('穿TShirst')
class Trouser(Finery):
def show(self):
Finery.show(self)
print ('穿裤子')
class Shoe(Finery):
def show(self):
Finery.show(self)
print ('穿鞋子')
class Tie(Finery):
def show(self):
Finery.show(self)
print ('穿领带')
if __name__ == '__main__':
person = Person('arron')
tshirt = TShirt()
trouser = Trouser()
shoe = Shoe()
tie = Tie()
trouser.decorator(tshirt)
shoe.decorator(trouser)
tie.decorator(shoe)
person.decorator(tie)
person.show()
输出:
arron开始穿衣 穿TShirst 穿裤子 穿鞋子 穿领带