【编程思想】【设计模式】【基础模式Fundamental】delegation_pattern

Python版

https://github.com/faif/python-patterns/blob/master/fundamental/delegation_pattern.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Reference: https://en.wikipedia.org/wiki/Delegation_pattern
Author: https://github.com/IuryAlves

*TL;DR80
Allows object composition to achieve the same code reuse as inheritance.
"""


class Delegator(object):
    """
    >>> delegator = Delegator(Delegate())
    >>> delegator.do_something("nothing")
    'Doing nothing'
    >>> delegator.do_anything()

    """

    def __init__(self, delegate):
        self.delegate = delegate

    def __getattr__(self, name):
        def wrapper(*args, **kwargs):
            if hasattr(self.delegate, name):
                attr = getattr(self.delegate, name)
                if callable(attr):
                    return attr(*args, **kwargs)
        return wrapper


class Delegate(object):

    def do_something(self, something):
        return "Doing %s" % something


if __name__ == '__main__':
    import doctest
    doctest.testmod()
Python转载版

猜你喜欢

转载自www.cnblogs.com/demonzk/p/9035700.html
今日推荐