Python Builder Pattern
The Builder Pattern lets us use the same construction process to create different object representations. Imagine the process of building a house: whether building a villa or an apartment, you go through steps like laying the foundation, building walls, and installing plumbing and electricity, yet the final results are completely different.
Core idea
The Builder Pattern separates the construction of a complex object from its representation, so the same construction process can create different representations. This pattern is especially suited to creating complex objects with multiple parts.
Why Do We Need the Builder Pattern?
Problems with Traditional Construction Methods
Let's first look at an example that does not use the Builder Pattern:
Example
class
Computer:
def
init
(
self
,
cpu
,
memory
,
storage
,
graphics_card
,
monitor
)
:
self
.
cpu
=
cpu
self
.
memory
=
memory
self
.
storage
=
storage
self
.
graphics_card
=
graphics_card
self
.
monitor
=
monitor
def
str
(
self
)
:
return
f
"Computer: CPU={self.cpu}, Memory={self.memory}GB, Storage={self.storage}GB, Graphics={self.graphics_card}, Monitor={self.monitor}"
Create a computer object
computer
=
Computer
(
"Intel i7"
,
16
,
512
,
"NVIDIA RTX 3060"
,
"27-inch 4K"
)
(
computer
)
Disadvantages of this approach:
- Too many constructor parameters, hard to maintain
- You must remember the order of all parameters
- The creation process is not flexible enough
- Poor code readability
Components of the Builder Pattern
The Builder Pattern contains four main roles:

1. Product
The complex object to be created
2. Builder (Abstract Builder)
Defines the abstract interface for creating each part of the product
3. ConcreteBuilder
Implements the Builder interface, constructs and assembles each part
4. Director
Constructs an object using the Builder interface
Complete Code Implementation
Let's fully implement the Builder Pattern with a computer configuration example:
1. Product Class
Example
class
Computer:
"""Computer product class"""
def
init
(
self
)
:
self
.
cpu
=
None
self
.
memory
=
None
self
.
storage
=
None
self
.
graphics_card
=
None
self
.
monitor
=
None
def
str
(
self
)
:
specs
=
[
]
if
self
.
cpu
:
specs.
append
(
f
"CPU: {self.cpu}"
)
if
self
.
memory
:
specs.
append
(
f
"Memory: {self.memory}GB"
)
if
self
.
storage
:
specs.
append
(
f
"Storage: {self.storage}GB"
)
if
self
.
graphics_card
:
specs.
append
(
f
"Graphics card: {self.graphics_card}"
)
if
self
.
monitor
:
specs.
append
(
f
"Monitor: {self.monitor}"
)
return
"Computer configuration:\n"
"\n"
.
join
(
f
" - {spec}"
for
spec
in
specs
)
2. Abstract Builder
Example
from
abc
import
ABC
,
abstractmethod
class
ComputerBuilder
(
ABC
)
:
"""Computer builder abstract class"""
def
init
(
self
)
:
self
.
computer
=
Computer
(
)
@
abstractmethod
def
build_cpu
(
self
)
:
pass
@
abstractmethod
def
build_memory
(
self
)
:
pass
@
abstractmethod
def
build_storage
(
self
)
:
pass
@
abstractmethod
def
build_graphics_card
(
self
)
:
pass
@
abstractmethod
def
build_monitor
(
self
)
:
pass
def
get_computer
(
self
)
:
return
self
.
computer
3. Concrete Builder
Example
class
GamingComputerBuilder
(
ComputerBuilder
)
:
"""Gaming computer builder"""
def
build_cpu
(
self
)
:
self
.
computer
.
cpu
=
"Intel i9-13900K"
def
build_memory
(
self
)
:
self
.
computer
.
memory
=
32
def
build_storage
(
self
)
:
self
.
computer
.
storage
=
2000
2TB
def
build_graphics_card
(
self
)
:
self
.
computer
.
graphics_card
=
"NVIDIA RTX 4090"
def
build_monitor
(
self
)
:
self
.
computer
.
monitor
=
"32-inch 4K 144Hz"
class
OfficeComputerBuilder
(
ComputerBuilder
)
:
"""Office computer builder"""
def
build_cpu
(
self
)
:
self
.
computer
.
cpu
=
"Intel i5-13400"
def
build_memory
(
self
)
:
self
.
computer
.
memory
=
16
def
build_storage
(
self
)
:
self
.
computer
.
storage
=
512
def
build_graphics_card
(
self
)
:
self
.
computer
.
graphics_card
=
"Integrated graphics"
def
build_monitor
(
self
)
:
self
.
computer
.
monitor
=
"24-inch 1080P"
4. Director
Example
class
ComputerDirector:
"""Computer build director"""
def
init
(
self
,
builder
)
:
self
.
builder
=
builder
def
construct_computer
(
self
)
:
"""The complete process of building a computer"""
self
.
builder
.
build_cpu
(
)
self
.
builder
.
build_memory
(
)
self
.
builder
.
build_storage
(
)
self
.
builder
.
build_graphics_card
(
)
self
.
builder
.
build_monitor
(
)
def
get_computer
(
self
)
:
return
self
.
builder
.
get_computer
(
)
Usage examples
Now let's see how to use the Builder Pattern to create different types of computers:
Example
def
main
(
)
:
(
"=== Builder Pattern Demo ===\n"
)
Create a gaming computer
(
"1. Build gaming computer:"
)
gaming_builder
=
GamingComputerBuilder
(
)
director
=
ComputerDirector
(
gaming_builder
)
director.
construct_computer
(
)
gaming_computer
=
director.
get_computer
(
)
(
gaming_computer
)
(
"\n"
"="
50
"\n"
)
Create an office computer
(
"2. Build office computer:"
)
office_builder
=
OfficeComputerBuilder
(
)
director
=
ComputerDirector
(
office_builder
)
director.
construct_computer
(
)
office_computer
=
director.
get_computer
(
)
(
office_computer
)
(
"\n"
"="
50
"\n"
)
Create a custom computer
(
"3. Custom computer build:"
)
custom_builder
=
CustomComputerBuilder
(
)
custom_builder.
build_cpu
(
"AMD Ryzen 7 7800X3D"
)
custom_builder.
build_memory
(
64
)
custom_builder.
build_storage
(
4000
)
custom_builder.
build_graphics_card
(
"AMD RX 7900 XTX"
)
custom_builder.
build_monitor
(
"34-inch curved ultrawide monitor"
)
custom_computer
=
custom_builder.
get_computer
(
)
(
custom_computer
)
Custom builder (optional step construction)
class
CustomComputerBuilder:
"""Custom computer builder"""
def
init
(
self
)
:
self
.
computer
=
Computer
(
)
def
build_cpu
(
self
,
cpu
)
:
self
.
computer
.
cpu
=
cpu
return
self
Returns itself to support chained calls
def
build_memory
(
self
,
memory
)
:
self
.
computer
.
memory
=
memory
return
self
def
build_storage
(
self
,
storage
)
:
self
.
computer
.
storage
=
storage
return
self
def
build_graphics_card
(
self
,
graphics_card
)
:
self
.
computer
.
graphics_card
=
graphics_card
return
self
def
build_monitor
(
self
,
monitor
)
:
self
.
computer
.
monitor
=
monitor
return
self
def
get_computer
(
self
)
:
return
self
.
computer
if
name
==
"main"
:
main
(
)
Variants of the Builder Pattern
1. Fluent Interface Builder
Example
class
Pizza:
def
init
(
self
)
:
self
.
size
=
None
self
.
cheese
=
False
self
.
pepperoni
=
False
self
.
mushrooms
=
False
def
str
(
self
)
:
ingredients
=
[
]
if
self
.
cheese
: ingredients.
append
(
"Cheese"
)
if
self
.
pepperoni
: ingredients.
append
(
"Pepperoni"
)
if
self
.
mushrooms
: ingredients.
append
(
"Mushrooms"
)
return
f
"{self.size}-inch pizza, toppings: {', '.join(ingredients)}"
class
PizzaBuilder:
def
init
(
self
,
size
)
:
self
.
pizza
=
Pizza
(
)
self
.
pizza
.
size
=
size
def
add_cheese
(
self
)
:
self
.
pizza
.
cheese
=
True
return
self
def
add_pepperoni
(
self
)
:
self
.
pizza
.
pepperoni
=
True
return
self
def
add_mushrooms
(
self
)
:
self
.
pizza
.
mushrooms
=
True
return
self
def
build
(
self
)
:
return
self
.
pizza
Using a fluent interface
pizza
=
(
PizzaBuilder
(
12
)
.
add_cheese
(
)
.
add_pepperoni
(
)
.
add_mushrooms
(
)
.
build
(
)
)
(
pizza
)
Pros and Cons of the Builder Pattern
Advantages
| Advantages | Description |
|---|---|
| Good encapsulation | Construction process is separated from representation; the client does not need to know internal details |
| Strong extensibility | New concrete builders can be added conveniently |
| Better control | The construction process can be controlled more finely |
| Code Readability | Code is clearer when using chained calls |
Disadvantages
| Disadvantages | Description |
|---|---|
| Increased complexity | Requires defining multiple classes, increasing system complexity |
| Not suitable when products differ greatly | If products differ greatly from each other, the Builder Pattern is not a good fit |
| Builder depends on the product | The builder needs to know the concrete details of the product |
Applicable scenarios
Situations suitable for the Builder Pattern:
- Creating complex objects: when you need to create complex objects with multiple parts
- Stable construction process: the construction process is relatively stable, but the parts of the object often change
- Multiple representations: the object to be created has multiple different representations
- Avoid overlapping constructors: avoid constructors with many parameters
Practical application example:
- Document converter: convert documents to different formats such as PDF, Word, HTML
- Meal preparation: prepare meals for different combos (combinations of burger, fries, drink)
- UI component construction: build complex user interface components
- Report generation: generate reports with different parts (header, data, charts)
Practical Exercise
Exercise 1: Implement a Car Builder
Try to implement a car Builder Pattern with the following components:
- Engine (gasoline, electric, hybrid)
- Body color (red, blue, black, white)
- Wheel size (16-inch, 18-inch, 20-inch)
- Interior (leather, fabric)
Exercise 2: Improve the Computer Builder
Add the following features to the computer builder:
- Optional components (e.g., whether to install an optical drive)
- Validation logic (e.g., memory cannot be less than 4GB)
- Price calculation feature
Summary
The Builder Pattern is a powerful creational design pattern that makes the creation process more flexible and controllable by breaking the construction of a complex object into multiple simple steps. Although it increases system complexity, in scenarios where complex objects need to be created and the construction process is relatively fixed, the Builder Pattern can significantly improve code maintainability and extensibility.
Remember the core idea of design patterns:Do not use patterns for the sake of using them, but to solve specific design problems. In real development, decide whether to use the Builder Pattern based on specific requirements.