forked from kiat/Elements-of-Software-Design
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_004_oop_decorator_pattern.py
60 lines (39 loc) · 1.65 KB
/
example_004_oop_decorator_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
56
57
58
59
60
"""The Decorator pattern is used to dynamically add a new features/functionalities
to an object without changing its implementation. It differs from inheritance because
the new functionalities are attached to that particular object on-demand,
not to the entire subclass."""
class HashTag: # pylint: disable=too-few-public-methods
"""Represents a hash tag text."""
def __init__(self, text):
"""A HastTag is a simple text string."""
self._text = text
def render(self):
"""This function represents a text rending in html format."""
return self._text
# def len(self):
# """Just in case if we want to know the lenght."""
# return len(self._text)
class BoldWrapper(HashTag): # pylint: disable=too-few-public-methods
"""Wraps a tag in <b>"""
def __init__(self, wrapped):
super().__init__(self)
self._wrapped = wrapped
def render(self):
return f"<b>{self._wrapped.render()}</b>"
class ItalicWrapper(HashTag): # pylint: disable=too-few-public-methods
"""Wraps a tag in <i>"""
def __init__(self, wrapped):
super().__init__(self)
self._wrapped = wrapped
def render(self):
return f"<i>{self._wrapped.render()}</i>"
def main():
"""This main function implements a test example run of this decorator pattern implementation"""
simple_hello = HashTag("#helloWorld!")
bold_hello = BoldWrapper(simple_hello)
italic_and_bold_hello = ItalicWrapper(bold_hello)
print("before: ", simple_hello.render())
print("after: ", bold_hello.render())
print("after: ", italic_and_bold_hello.render())
if __name__ == "__main__":
main()