Python设计模式——装饰模式(decorator)
装饰模式(decorator)
装饰模式是在原有对象的基础上,动态增加一个新的特性。与继承的最大区别是,这种新增特性是比较泛化的,可以被多种对象增加。
示例
# 原对象
class TextTag:
"""Represents a base text tag"""
def __init__(self, text):
self._text = text
def render(self):
return self._text
# 装饰1
class BoldWrapper(TextTag):
"""Wraps a tag in <b>"""
def __init__(self, wrapped):
self._wrapped = wrapped
def render(self):
return f"<b>{self._wrapped.render()}</b>"
# 装饰2
class ItalicWrapper(TextTag):
"""Wraps a tag in <i>"""
def __init__(self, wrapped):
self._wrapped = wrapped
def render(self):
return f"<i>{self._wrapped.render()}</i>"
# 调用:
if __name__ == '__main__':
simple_hello = TextTag("hello, world!")
special_hello = ItalicWrapper(BoldWrapper(simple_hello))
print("before:", simple_hello.render())
# 预期输出
# before: hello, world!
print("after:", special_hello.render())
# 预期输出
# after: <i><b>hello, world!</b></i>
装饰器
以上示例中的装饰模式采用的是最原始的方式,需要对输入一个对象,通过装饰函数/类,得到被装饰的对象。实际上,在python中更常用的是通过函数装饰器或者类装饰器,直接将对象所属的类进行装饰。
关于装饰器的一次随笔
本文来自博客园,作者:坦先生的AI资料室,转载请注明原文链接:https://www.cnblogs.com/yushengchn/p/16521928.html