CreationalPythonverifiedVerified

Builder Pattern in Python

Separates the construction of a complex object from its representation, allowing the same construction process to produce different results.

How to Implement the Builder Pattern in Python

1Step 1: Define the product dataclass

from dataclasses import dataclass, field


@dataclass
class House:
    walls: int = 0
    doors: int = 0
    windows: int = 0
    has_garage: bool = False
    has_pool: bool = False

    def describe(self) -> str:
        features = [
            f"{self.walls} walls",
            f"{self.doors} doors",
            f"{self.windows} windows",
            *(["garage"] if self.has_garage else []),
            *(["pool"] if self.has_pool else []),
        ]
        return f"House with {', '.join(features)}"

2Step 2: Create the Builder with a fluent API

class HouseBuilder:
    def __init__(self) -> None:
        self._house = House()

    def reset(self) -> "HouseBuilder":
        self._house = House()
        return self

    def set_walls(self, n: int) -> "HouseBuilder":
        self._house.walls = n
        return self

    def set_doors(self, n: int) -> "HouseBuilder":
        self._house.doors = n
        return self

    def set_windows(self, n: int) -> "HouseBuilder":
        self._house.windows = n
        return self

    def set_garage(self, v: bool) -> "HouseBuilder":
        self._house.has_garage = v
        return self

    def set_pool(self, v: bool) -> "HouseBuilder":
        self._house.has_pool = v
        return self

    def build(self) -> House:
        result = self._house
        self.reset()
        return result

3Step 3: Add a Director for preset configurations

class Director:
    def build_minimal(self, b: HouseBuilder) -> House:
        return b.reset().set_walls(4).set_doors(1).set_windows(2).build()

    def build_luxury(self, b: HouseBuilder) -> House:
        return (
            b.reset()
            .set_walls(8).set_doors(4).set_windows(12)
            .set_garage(True).set_pool(True)
            .build()
        )

4Step 4: Build houses with and without a director

builder = HouseBuilder()
director = Director()

print(director.build_minimal(builder).describe())
print(director.build_luxury(builder).describe())

custom = builder.set_walls(6).set_doors(2).set_windows(8).set_pool(True).build()
print(custom.describe())

Builder Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Builder Pattern in the Real World

Consider ordering a custom sandwich at a deli. You tell the sandwich artist (builder) each step — bread type, protein, toppings, sauce — and they assemble it in the right order. You don’t need to know how to layer ingredients properly; you just specify what you want, and the builder hands you a finished sandwich.