forked from tuvo1106/python_design_patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder.py
More file actions
105 lines (82 loc) · 2.38 KB
/
builder.py
File metadata and controls
105 lines (82 loc) · 2.38 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""
Builder
- When piecewise object construction is complicated,
provide an API for doing it succinctly
Motivation
- some objects are simply and can be created in a single
initializer call
- other objects require a lot of ceremony to create
- having an object with 10 initializer arguments is not
productive
- instead, opt for piecewise construction
- Builder provides an API for constructing an object
step-by-step
"""
# simple scenario
TEXT = 'hello'
PARTS = ['<p>', TEXT, '</p>']
print(''.join(PARTS))
# more complicated
WORDS = ['hello', 'world']
PARTS = ['<ul>']
for w in WORDS:
PARTS.append(f'\t<li>{w}</li>')
PARTS.append('</ul>')
print('\n'.join(PARTS))
class HtmlElement:
indent_size = 2
def __init__(self, name="", text=""):
self.name = name
self.text = text
self.elements = []
def __str(self, indent):
lines = []
i = ' ' * (indent * self.indent_size)
lines.append(f'{i}<{self.name}>')
if self.text:
i1 = ' ' * ((indent + 1) * self.indent_size)
lines.append(f'{i1}{self.text}')
for e in self.elements:
lines.append(e.__str(indent + 1))
lines.append(f'{i}</{self.name}>')
return '\n'.join(lines)
def __str__(self):
return self.__str(0)
@staticmethod
def create(name):
return HtmlBuilder(name)
class HtmlBuilder:
__root = HtmlElement()
def __init__(self, root_name):
self.root_name = root_name
self.__root.name = root_name
# not fluent
def add_child(self, child_name, child_text):
self.__root.elements.append(
HtmlElement(child_name, child_text)
)
# fluent
def add_child_fluent(self, child_name, child_text):
self.__root.elements.append(
HtmlElement(child_name, child_text)
)
return self
def clear(self):
self.__root = HtmlElement(name=self.root_name)
def __str__(self):
return str(self.__root)
BUILDER = HtmlBuilder('ul')
BUILDER.add_child('li', 'hello')
BUILDER.add_child('li', 'world')
print('Ordinary builder:')
print(BUILDER)
# chaining methods
FLUENT = HtmlBuilder('ul')
FLUENT.add_child_fluent('li', 'hello').add_child_fluent('li', 'world')
print('Fluent builder:')
print(FLUENT)
# create
CREATED = HtmlElement.create('ul')
CREATED.add_child_fluent('li', 'python')
print('Created builder:')
print(CREATED)