This builder method is a rare design pattern that helps us in building a complicated object using simple objects and using an algorithmic approach. Exceptionally, the builder’s method is beneficial when we need to create an object(complex) with lots of possible configuration options, it’s a type of creational design pattern.
For example, you happen to be an engineer at BMW and the project on building a bike using a Design pattern was assigned. The design pattern suggested was the Builder Method, and since python is easily and widely recognized, it turns out to be the best option.
So the implementation of the Bike project is implemented below using the Builder method.
#Engineer class Engineer: __builder = None def setBuilder(self, builder): self.__builder = builder def getBike(self): bike = Bike() # First goes the body body = self.__builder.getBody() bike.setBody(body) # Then engine engine = self.__builder.getEngine() bike.setEngine(engine) # And four tires for i in range(4): tire = self.__builder.getTire() bike.attachTire(tire) return bike # The whole product class Bike: def __init__(self): self.__tires = list() self.__engine = None self.__body = None def setBody(self, body): self.__body = body def attachTire(self, tire): self.__tires.append(tire) def setEngine(self, engine): self.__engine = engine def specification(self): print ("body: %s" % self.__body.shape) print ("engine horsepower: %d" % self.__engine.horsepower) print ("tire size: %d\'" % self.__tires.size) class Builder: def getTire(self): pass def getEngine(self): pass def getBody(self): pass class BMWBuilder(Builder): def getTire(self): tire = Tire() tire.size = 53 return tire def getEngine(self): engine = Engine() engine.horsepower = 690 return engine def getBody(self): body = Body() body.shape = "BMW C690" return body # Bike parts class Tire: size = None class Engine: horsepower = None class Body: shape = None def main(): bmwBuilder = BMWBuilder() # initializing the class engineer = Engineer() # Build Jeep print ("Jeep") engineer.setBuilder(bmwBuilder) bmwbike = engineer.getBike() bmwbike.specification() print ("") if __name__ == "__main__": main()
From the code above code, we have seven different classes starting from the Engineer down to all parts he is to use for the Bike.
The above program generates the output below:
ProBook:~/InfosecAddicts/python design pattern$ python builder.py BMW body: BMW C690 engine horsepower: 690 tire size: 53'
So from the output, The name of the Bike was displayed alongside the body model, engine horsepower and tire size.
Pros and Cons
- Object Construction
- Code Reusability
- Single Responsibility Principle
- Code initialization
- Increase in code complexity