forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delegation_pattern.py
55 lines (41 loc) · 1.18 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Reference: https://en.wikipedia.org/wiki/Delegation_pattern
Author: https://github.com/IuryAlves
*TL;DR
Allows object composition to achieve the same code reuse as inheritance.
"""
class Delegator(object):
"""
>>> delegator = Delegator(Delegate())
>>> delegator.p1
123
>>> delegator.p2
Traceback (most recent call last):
...
AttributeError: 'Delegate' object has no attribute 'p2'
>>> delegator.do_something("nothing")
'Doing nothing'
>>> delegator.do_anything()
Traceback (most recent call last):
...
AttributeError: 'Delegate' object has no attribute 'do_anything'
"""
def __init__(self, delegate):
self.delegate = delegate
def __getattr__(self, name):
attr = getattr(self.delegate, name)
if not callable(attr):
return attr
def wrapper(*args, **kwargs):
return attr(*args, **kwargs)
return wrapper
class Delegate(object):
def __init__(self):
self.p1 = 123
def do_something(self, something):
return "Doing %s" % something
if __name__ == '__main__':
import doctest
doctest.testmod()