forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.py
95 lines (65 loc) · 2.15 KB
/
builder.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
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
#!/usr/bin/python
# -*- coding : utf-8 -*-
"""
*What is this pattern about?
It decouples the creation of a complex object and its representation,
so that the same process can be reused to build objects from the same
family.
This is useful when you must separate the specification of an object
from its actual representation (generally for abstraction).
*What does this example do?
This particular example uses a director function to abstract the
construction of a building. The user specifies a Builder (House or
Flat) and the director specifies the methods in the order necessary,
creating a different building depending on the specification
(from the Builder class).
@author: Diogenes Augusto Fernandes Herminio <[email protected]>
https://gist.github.com/420905#file_builder_python.py
*Where is the pattern used practically?
*References:
https://sourcemaking.com/design_patterns/builder
*TL;DR80
Decouples the creation of a complex object and its representation.
"""
def construct_building(builder):
builder.new_building()
builder.build_floor()
builder.build_size()
return builder.building
# Abstract Builder
class Builder(object):
def __init__(self):
self.building = None
def new_building(self):
self.building = Building()
def build_floor(self):
raise NotImplementedError
def build_size(self):
raise NotImplementedError
# Concrete Builder
class BuilderHouse(Builder):
def build_floor(self):
self.building.floor = 'One'
def build_size(self):
self.building.size = 'Big'
class BuilderFlat(Builder):
def build_floor(self):
self.building.floor = 'More than One'
def build_size(self):
self.building.size = 'Small'
# Product
class Building(object):
def __init__(self):
self.floor = None
self.size = None
def __repr__(self):
return 'Floor: {0.floor} | Size: {0.size}'.format(self)
# Client
if __name__ == "__main__":
building = construct_building(BuilderHouse())
print(building)
building = construct_building(BuilderFlat())
print(building)
### OUTPUT ###
# Floor: One | Size: Big
# Floor: More than One | Size: Small