Skip to content

Commit f542cb8

Browse files
committed
Creational pattern => Builder
1 parent 5b823f3 commit f542cb8

File tree

1 file changed

+116
-0
lines changed

1 file changed

+116
-0
lines changed

builder.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
"""
2+
Creational :
3+
Builder => every builders designed patterns has director class to attach
4+
each side of objects
5+
"""
6+
7+
8+
class Director:
9+
__builder = None
10+
11+
def set_builder(self, builder):
12+
self.__builder = builder
13+
14+
def get_car(self):
15+
car = Car()
16+
17+
body = self.__builder.get_body()
18+
car.set_body(body)
19+
20+
wheel = self.__builder.get_wheel()
21+
car.set_wheel(wheel)
22+
23+
engine = self.__builder.get_engine()
24+
car.set_engine(engine)
25+
return car
26+
27+
28+
# ----------------------------------------
29+
class Car:
30+
def __init__(self):
31+
self.__wheel = None
32+
self.__engine = None
33+
self.__body = None
34+
35+
def set_wheel(self, wheel):
36+
self.__wheel = wheel
37+
38+
def set_body(self, body):
39+
self.__body = body
40+
41+
def set_engine(self, engine):
42+
self.__engine = engine
43+
44+
def detail(self):
45+
print(f'Body: {self.__body.shape}')
46+
print(f'Engine: {self.__engine.hp}')
47+
print(f'Wheel: {self.__wheel.size}')
48+
49+
50+
# ----------------------------------------
51+
class Builder:
52+
def get_engine(self):
53+
pass
54+
55+
def get_wheel(self):
56+
pass
57+
58+
def get_body(self):
59+
pass
60+
61+
62+
class Benz(Builder):
63+
def get_body(self):
64+
body = Body()
65+
body.shape = 'Suv'
66+
return body
67+
68+
def get_engine(self):
69+
engine = Engine()
70+
engine.hp = 500
71+
return engine
72+
73+
def get_wheel(self):
74+
wheel = Wheel()
75+
wheel.size = 22
76+
return wheel
77+
78+
79+
class Bmw(Builder):
80+
def get_body(self):
81+
body = Body()
82+
body.shape = 'Sedan'
83+
return body
84+
85+
def get_engine(self):
86+
engine = Engine()
87+
engine.hp = 340
88+
return engine
89+
90+
def get_wheel(self):
91+
wheel = Wheel()
92+
wheel.size = 18
93+
return wheel
94+
95+
96+
# ----------------------------------------
97+
class Wheel:
98+
size = None
99+
100+
101+
class Body:
102+
shape = None
103+
104+
105+
class Engine:
106+
hp = None
107+
108+
109+
# ----------------------------------------
110+
111+
112+
car1 = Bmw()
113+
director = Director()
114+
director.set_builder(car1)
115+
b1 = director.get_car()
116+
b1.detail()

0 commit comments

Comments
 (0)