Builder

creational

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

Intent

The Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.

Motivation

When creating a complex object requires many steps, the Builder pattern lets you construct objects step by step. It's useful when an object needs to be created with many possible configurations.

Structure

The pattern involves a Builder interface that specifies methods for creating parts of a Product object. ConcreteBuilder classes implement the Builder interface. A Director class constructs an object using the Builder interface.

Participants

  • Builder - specifies an abstract interface for creating parts of a Product object
  • ConcreteBuilder - constructs and assembles parts of the product
  • Director - constructs an object using the Builder interface
  • Product - represents the complex object under construction

Pros

  • Allows you to vary a product's internal representation
  • Isolates code for construction and representation
  • Gives finer control over the construction process
  • Follows Single Responsibility Principle

Cons

  • Increases overall code complexity
  • Requires creating multiple new classes

Use Cases

Creating complex DOM structures
Building SQL queries
Constructing meals in restaurants
Assembling vehicles with different options
Creating HTTP requests

Implementation Tips

Considerations

  • Define a clear interface for building parts
  • Decide whether Director is necessary
  • Consider fluent interface for builder methods

Tips

  • Use method chaining for a fluent API
  • Make the builder return itself from setter methods
  • Consider providing default values
  • Make the build() method return the final product

Interactive Code Editor