Skip to content

Commit b9f64a7

Browse files
authored
Merge pull request faif#155 from lucasloisp/decorator-pattern
Implemented the correct Decorator Pattern (Issue faif#150)
2 parents 2ccf769 + ac5ea8b commit b9f64a7

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

decorator.py

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,41 @@
11
#!/usr/bin/env python
2-
"""https://docs.python.org/2/library/functools.html#functools.wraps"""
3-
"""https://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/739665#739665"""
2+
"""
3+
Reference: https://en.wikipedia.org/wiki/Decorator_pattern
4+
"""
45

5-
from functools import wraps
66

7+
class TextTag(object):
8+
"""Represents a base text tag"""
9+
def __init__(self, text):
10+
self._text = text
711

8-
def makebold(fn):
9-
return getwrapped(fn, "b")
12+
def render(self):
13+
return self._text
1014

1115

12-
def makeitalic(fn):
13-
return getwrapped(fn, "i")
16+
class BoldWrapper(object):
17+
"""Wraps a tag in <b>"""
18+
def __init__(self, wrapped):
19+
self._wrapped = wrapped
1420

21+
def render(self):
22+
return "<b>{}</b>".format(self._wrapped.render())
1523

16-
def getwrapped(fn, tag):
17-
@wraps(fn)
18-
def wrapped():
19-
return "<%s>%s</%s>" % (tag, fn(), tag)
20-
return wrapped
2124

25+
class ItalicWrapper(object):
26+
"""Wraps a tag in <i>"""
27+
def __init__(self, wrapped):
28+
self._wrapped = wrapped
2229

23-
@makebold
24-
@makeitalic
25-
def hello():
26-
"""a decorated hello world"""
27-
return "hello world"
30+
def render(self):
31+
return "<i>{}</i>".format(self._wrapped.render())
2832

2933
if __name__ == '__main__':
30-
print('result:{} name:{} doc:{}'.format(hello(), hello.__name__, hello.__doc__))
34+
simple_hello = TextTag("hello, world!")
35+
special_hello = ItalicWrapper(BoldWrapper(simple_hello))
36+
print("before:", simple_hello.render())
37+
print("after:", special_hello.render())
3138

3239
### OUTPUT ###
33-
# result:<b><i>hello world</i></b> name:hello doc:a decorated hello world
40+
# before: hello, world!
41+
# after: <i><b>hello, world!</b></i>

0 commit comments

Comments
 (0)