读书人

python实现Decorator形式

发布时间: 2013-09-11 16:26:28 作者: rapoo

python实现Decorator模式
#-*-coding:utf-8-*-


'''
意图:动态地给一个对象添加一些额外的职责。比通过生成子类更为灵活
'''
from abc import ABCMeta

class Component():
__metaclass__ = ABCMeta
def __init__(self):
pass
def operation(self):
pass

class ConcreteComponent(Component):
def operation(self):
print 'ConcreteComponent operation...'

class Decorator(Component):
def __init__(self, comp):
self._comp = comp
def operation(self):
pass

class ConcreteDecorator(Decorator):
def operation(self):
self._comp.operation()
self.addedBehavior()
def addedBehavior(self):
print 'ConcreteDecorator addedBehavior...'

if __name__ == "__main__":
comp = ConcreteComponent()
dec = ConcreteDecorator(comp)
dec.operation()


读书人网 >perl python

热点推荐