forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator.py
41 lines (30 loc) · 966 Bytes
/
decorator.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
#!/usr/bin/env python
"""
Reference: https://en.wikipedia.org/wiki/Decorator_pattern
"""
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>