zoukankan      html  css  js  c++  java
  • 【编程思想】【设计模式】【结构模式Structural】装饰模式decorator

    Python版

    https://github.com/faif/python-patterns/blob/master/structural/decorator.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    """
    *What is this pattern about?
    The Decorator pattern is used to dynamically add a new feature to an
    object without changing its implementation. It differs from
    inheritance because the new feature is added only to that particular
    object, not to the entire subclass.
    
    *What does this example do?
    This example shows a way to add formatting options (boldface and
    italic) to a text by appending the corresponding tags (<b> and
    <i>). Also, we can see that decorators can be applied one after the other,
    since the original text is passed to the bold wrapper, which in turn
    is passed to the italic wrapper.
    
    *Where is the pattern used practically?
    The Grok framework uses decorators to add functionalities to methods,
    like permissions or subscription to an event:
    http://grok.zope.org/doc/current/reference/decorators.html
    
    *References:
    https://sourcemaking.com/design_patterns/decorator
    
    *TL;DR80
    Adds behaviour to object without affecting its class.
    """
    
    from __future__ import print_function
    
    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>
    Python转载版
  • 相关阅读:
    基础字段及选项2(11)
    模型层及ORM介绍(9)
    Luogu [P3367] 模板 并查集
    Luogu [P1958] 上学路线_NOI导刊2009普及(6)
    Luogu [P3951] 小凯的疑惑
    Luogu [P2708] 硬币翻转
    Luogu [P1334] 瑞瑞的木板(手写堆)
    一步步学习如何建立自己的个性博客~~
    Android初学者—listView用法
    SQLite命令—对表插入和修改等操作
  • 原文地址:https://www.cnblogs.com/demonzk/p/9035420.html
Copyright © 2011-2022 走看看