forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delegation_pattern.py
42 lines (30 loc) · 933 Bytes
/
delegation_pattern.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/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()