Builder Pattern: What It Is and How It Works
builder pattern is a design pattern that helps create complex objects step-by-step, separating the construction process from the final object. It allows you to build different representations of an object using the same construction process.How It Works
Imagine you want to build a custom sandwich. You choose the bread, the fillings, the sauces, and the toppings one by one. The builder pattern works similarly by letting you create an object step-by-step, deciding each part separately.
Instead of making a complex object all at once, the builder pattern breaks down the creation into smaller steps. A builder class handles these steps, and a director can control the order of building. This way, you can create different versions of the object by changing the steps or their order without changing the final object's code.
Example
This example shows how to build a simple House object step-by-step using the builder pattern.
class House { constructor() { this.windows = 0; this.doors = 0; this.hasGarage = false; } } class HouseBuilder { constructor() { this.house = new House(); } addWindows(count) { this.house.windows = count; return this; } addDoors(count) { this.house.doors = count; return this; } addGarage() { this.house.hasGarage = true; return this; } build() { return this.house; } } // Using the builder const builder = new HouseBuilder(); const myHouse = builder.addWindows(4).addDoors(2).addGarage().build(); console.log(myHouse);
When to Use
Use the builder pattern when you need to create complex objects with many parts or options, especially when the construction process must allow different configurations.
For example, it is useful in building user interfaces, assembling complex documents, or creating objects with many optional parameters. It helps keep code clean and flexible by separating object construction from its representation.
Key Points
- The builder pattern separates object construction from its representation.
- It builds objects step-by-step, allowing different configurations.
- It improves code readability and flexibility for complex object creation.
- Common roles: Builder (build steps), Director (controls building process), and Product (final object).