The builder pattern

The Builder pattern is a creational design pattern that allows you to create complex objects step by step by using a builder object.


class Director:
    def __init__(self):
        self._builder = None

    def set_builder(self, builder):
        self._builder = builder

    def get_car(self):
        car = Car()

        body = self._builder.get_body()
        car.set_body(body)

        engine = self._builder.get_engine()
        car.set_engine(engine)

        return car

class Builder:
    def get_body(self):
        pass

    def get_engine(self):
        pass

class Car:
    def __init__(self):
        self._body = None
        self._engine = None

    def set_body(self, body):
        self._body = body

    def set_engine(self, engine):
        self._engine = engine

    def __str__(self):
        return f"Body: {self._body.shape} | Engine: {self._engine.type}"

class SUVBody:
    shape = "SUV"

class SedanBody:
    shape = "Sedan"

class SUVEngine:
    type = "V8"

class SedanEngine:
    type = "V6"

class SUVBuilder(Builder):
    def get_body(self):
        return SUVBody()

    def get_engine(self):
        return SUVEngine()

class SedanBuilder(Builder):
    def get_body(self):
        return SedanBody()

    def get_engine(self):
        return SedanEngine()

director = Director()

suv_builder = SUVBuilder()
director.set_builder(suv_builder)
suv = director.get_car()
print(suv) # Body: SUV | Engine: V8

sedan_builder = SedanBuilder()
director.set_builder(sedan_builder)
sedan = director.get_car()
print(sedan) # Body: Sedan | Engine: V6

In this example, the Director class is the director class that has a Builder object and is responsible for constructing a car using the builder. The Builder class is an abstract class that defines the interface for creating the parts of the car. The Car class is the class that represents the car and has attributes for the body and engine. The SUVBuilder and SedanBuilder classes are concrete builder classes that implement the Builder interface and create specific types of bodies and engines for SUVs and sedans, respectively. The director creates a builder and sets it using the set_builder method. It then uses the builder to construct a car by calling the get_body and get_engine methods of the builder and setting the corresponding attributes of the car. The director returns the car object when it is finished building it.