Builder
Lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.
classDiagram
class Director {
-Builder builder
+construct()
}
class Builder {
<<interface>>
+buildPartA()
+buildPartB()
+buildPartC()
+getResult() Product
}
class ConcreteBuilder1 {
-Product result
+buildPartA()
+buildPartB()
+buildPartC()
+getResult() Product
+reset()
}
class Product {
-Array parts
+add(part)
+listParts()
}
Director o-- Builder
Builder <|.. ConcreteBuilder1
ConcreteBuilder1 ..> Product
When to use
Use the Builder pattern to get rid of a “telescoping constructor”. Use when you want your code to be able to create different representations of some product (for example, stone and wooden houses).
Explanation
Problem
Imagine a complex object that requires laborious, step-by-step initialization of many fields and nested objects. Such initialization code is usually buried inside a monstrous constructor with lots of parameters. Or even worse: scattered all over the client code.
Solution
The Builder pattern suggests that you extract the object construction code out of its own class and move it to separate objects called builders. The pattern organizes object construction into a set of steps (buildWalls, buildDoor, etc.). To create an object, you execute a series of these steps on a builder object. The important part is that you don’t need to call all of the steps. You can call only those steps that are necessary for producing a particular configuration of an object.
Real world problem
- House Construction: Building a house can be simple (walls, floor, roof) or complex (swimming pool, statue, garden).
- SQL Query Builder: Constructing a SQL query string (SELECT, FROM, WHERE, JOIN) step by step.
- Document Generation: Generating a report (Header, Body, Footer) where different builders produce HTML, PDF, or Plain Text.
Pros and Cons
| Pros | Cons |
|---|---|
| - Control: You can construct objects step-by-step, defer construction steps or run steps recursively. - Reusability: You can reuse the same construction code when building various representations of products. - Single Responsibility Principle: You can isolate complex construction code from the business logic of the product. |
- Complexity: The overall complexity of the code increases since the pattern requires creating multiple new classes. |
Comparison
- Factory Method: Factory Method mainly creates objects in a single step. Builder constructs them step by step.
- Abstract Factory: Abstract Factory is specialized in creating families of related products. Builder creates complex objects.
- Composite: Builders often construct Composite trees.
Code example
Typescript
Php