Skip to content

Commit 958e128

Browse files
committed
add Builder pattern
1 parent c1ad9b1 commit 958e128

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

builder/Builder.py

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
#
2+
# Python Design Patterns: Builder
3+
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
4+
# 2016
5+
#
6+
# Source code is licensed under MIT License
7+
# (for more details see LICENSE)
8+
#
9+
10+
import sys
11+
12+
#
13+
# Product
14+
# the final object that will be created using Builder
15+
#
16+
class Product:
17+
def __init__(self):
18+
self._partA = ""
19+
self._partB = ""
20+
self._partC = ""
21+
22+
def makeA(self, part):
23+
self._partA = part
24+
25+
def makeB(self, part):
26+
self._partB = part
27+
28+
def makeC(self, part):
29+
self._partC = part
30+
31+
def get(self):
32+
return self._partA +" "+ self._partB +" "+ self._partC
33+
34+
#
35+
# Builder
36+
# abstract interface for creating products
37+
#
38+
class Builder:
39+
def __init__(self):
40+
self._product = Product()
41+
42+
def get(self):
43+
return self._product
44+
45+
def buildPartA():
46+
pass
47+
48+
def buildPartB():
49+
pass
50+
51+
def buildPartC():
52+
pass
53+
54+
#
55+
# Concrete Builders
56+
# create real products and stores them in the composite structure
57+
#
58+
class ConcreteBuilderX(Builder):
59+
def __init__(self):
60+
Builder.__init__(self)
61+
62+
def buildPartA(self):
63+
self._product.makeA("A-X")
64+
65+
def buildPartB(self):
66+
self._product.makeB("B-X")
67+
68+
def buildPartC(self):
69+
self._product.makeC("C-X")
70+
71+
class ConcreteBuilderY(Builder):
72+
def __init__(self):
73+
Builder.__init__(self)
74+
75+
def buildPartA(self):
76+
self._product.makeA("A-Y")
77+
78+
def buildPartB(self):
79+
self._product.makeB("B-Y")
80+
81+
def buildPartC(self):
82+
self._product.makeC("C-Y")
83+
84+
#
85+
# Director
86+
# responsible for managing the correct sequence of object creation
87+
#
88+
class Director:
89+
def __init__(self):
90+
self._builder = None
91+
92+
def set(self, builder):
93+
self._builder = builder
94+
95+
def get(self):
96+
return self._builder.get()
97+
98+
def construct(self):
99+
self._builder.buildPartA()
100+
self._builder.buildPartB()
101+
self._builder.buildPartC()
102+
103+
104+
if __name__ == "__main__":
105+
builderX = ConcreteBuilderX()
106+
builderY = ConcreteBuilderY()
107+
108+
director = Director()
109+
director.set(builderX)
110+
director.construct()
111+
112+
product1 = director.get()
113+
print("1st product parts: " + product1.get())
114+
115+
director.set(builderY)
116+
director.construct()
117+
118+
product2 = director.get()
119+
print("2nd product parts: " + product2.get())
120+

0 commit comments

Comments
 (0)