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转载版
  • 相关阅读:
    兼容ie6的mvvm框架--san
    Parsing error: The keyword 'export' is reserved && error Parsing error: Unexpected token <
    Call to undefined function openssl_decrypt()
    css 陌生属性
    获取url
    relative 和 absolute
    SSL certificate problem: unable to get local issuer certificate 的解决方法
    使用wamp扩展php时出现服务未启动的解决方法
    php判断是不是移动设备
    js:不是空字符串的空字符串引起的bug
  • 原文地址:https://www.cnblogs.com/demonzk/p/9035420.html
Copyright © 2011-2022 走看看