def
动态地给一个对象添加一些额外的职责。就增加功能来说, 装饰模式相比生成子类更为灵活。
usage
装饰类和被装饰类可以独立发展, 而不会相互耦合。 换句话说, Component类无须知道Decorator类, Decorator类是从外部来扩展Component类的功能, 而Decorator也不用知道具体的构件。
装饰模式是继承关系的一个替代方案。 我们看装饰类Decorator, 不管装饰多少层, 返回的对象还是Component, 实现的还是is-a的关系。
装饰模式可以动态地扩展一个实现类的功能, 这不需要多说, 装饰模式的定义就是如此。
code
class TextTag(object):
"""Represents a base text tag"""
def __init__(self, text):
self._text = text
def render(self):
return self._text
class BoldWrapper(TextTag):
"""Wraps a tag in <b>"""
def __init__(self, wrapped):
self._wrapped = wrapped
def render(self):
return "<b>{}</b>".format(self._wrapped.render())
class ItalicWrapper(TextTag):
"""Wraps a tag in <i>"""
def __init__(self, wrapped):
self._wrapped = wrapped
def render(self):
return "<i>{}</i>".format(self._wrapped.render())
if __name__ == '__main__':
simple_hello = TextTag("hello, world!")
special_hello = ItalicWrapper(BoldWrapper(simple_hello))
print("before:", simple_hello.render())
print("after:", special_hello.render())
### OUTPUT ###
# before: hello, world!
# after: <i><b>hello, world!</b></i>