Builder

Category

Creational pattern

Problem

Create complex objects step by step. The same construction process can create different representations. Useful when an object requires many parameters, some optional, and you want to avoid telescoping constructors.

Solution

  • Separate object construction from its representation
  • Create a Builder class with methods for setting each part of the object
  • A Director or fluent interface guides the construction process
  • The final object is retrieved from the Builder after all parts are set

Structure

  • Product: The complex object being built
  • Builder: Interface for creating parts of the Product
  • ConcreteBuilder: Implements the Builder interface; tracks the representation it creates
  • Director: Constructs an object using the Builder interface
  • Client: Creates the Builder, configures it, and retrieves the Product

Key Benefits

  • Step-by-step construction — Control over the creation process
  • Immutable objects — The Product can be made immutable once built
  • Fluent API — Method chaining provides a readable, expressive interface
  • Same process, different results — Different builders can create different representations

Trade-offs

  • More code — Requires creating Builder classes for each product type
  • Overkill for simple objects — Adds unnecessary complexity for basic construction

When to Use

  • The algorithm for creating a complex object should be independent of the parts that make up the object
  • Construction must allow different representations for the constructed object
  • You want to avoid a telescoping constructor (many parameters)
  • You need to construct an object in a specific order with optional parameters

Examples