Sobes.tech
Middle

What is the 'Builder' design pattern?

sobes.tech AI

Answer from AI

The "Builder" pattern is a creational design pattern that allows constructing a complex object step by step, providing different representations and construction options. It separates the construction process of a complex object from its representation.

Main components:

  • Builder: An interface or abstract class defining the steps for creating parts of the product.
  • ConcreteBuilder: A specific implementation of Builder that performs the construction steps and provides a method to get the finished product. It contains a reference to the Product being built.
  • Product: The complex object being constructed.
  • Director: (Optional) Defines the order of construction steps. It can manage the process of creating a specific object using the Builder.

Advantages:

  • Allows creating complex objects step by step, simplifying the code and making it more readable.
  • Enables different representations of the same construction process.
  • Isolates the construction code from the object's business logic.

Example:

# Product
class House:
    def __init__(self):
        self.walls = 0
        self.windows = 0
        self.doors = 0
        self.roof = False

    def __str__(self):
        return f"House with {self.walls} walls, {self.windows} windows, {self.doors} doors, and roof: {self.roof}"

# Builder interface
class HouseBuilder:
    def reset(self):
        pass

    def build_walls(self, count):
        pass

    def build_windows(self, count):
        pass

    def build_doors(self, count):
        pass

    def build_roof(self):
        pass

    def get_result(self):
        pass

# Concrete builder
class StoneHouseBuilder(HouseBuilder):
    def __init__(self):
        self._house = House()

    def reset(self):
        self._house = House()

    def build_walls(self, count):
        self._house.walls = count

    def build_windows(self, count):
        self._house.windows = count

    def build_doors(self, count):
        self._house.doors = count

    def build_roof(self):
        self._house.roof = True

    def get_result(self):
        return self._house

# Director (optional)
class Director:
    def construct_simple_house(self, builder):
        builder.reset()
        builder.build_walls(4)
        builder.build_windows(2)
        builder.build_doors(1)
        builder.build_roof()

# Usage
builder = StoneHouseBuilder()
director = Director()

director.construct_simple_house(builder)
simple_house = builder.get_result()
print(simple_house)

# Building a house differently without a director
builder.reset()
builder.build_walls(6)
builder.build_windows(4)
builder.build_doors(2)
complex_house = builder.get_result()
print(complex_house)