Builder Design Pattern

builder design pattern image

Separate the construction of a complex object from its representation so that the same construction process can create different representations. (dofactory)

  • Builder specifies an abstract interface for creating parts of a Product object
  • ConcreteBuilder constructs and assembles parts of the product by implementing the Builder interface. It defines and keeps track of the representation it creates and provides an interface for retrieving the product
  • Director constructs an object using the Builder interface
  • Product represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled. It  includes classes that define the constituent parts, including interfaces for assembling the parts into the final result

  • An application needs to create the elements of a complex aggregate.
  • The creation algorithm of a complex object is independent from the parts that actually compose the object and  system needs to allow different representations for the objects that are being built. 
  • Builders are good candidates for a fluent interface.
  • An example of the pattern in .NET and also Java API is StringBuilder. 

  • Separate the construction of a complex object from its representation
  • Same construction process can create different representation
  • Having control over the creation process at runtime

  • I do not see a particular downside for this pattern, However, builder pattern is not a good choice if the object to construct needs to be immutable.

Sample Code
Classic builder pattern example

Fluent interface builder example

Related Patterns
  • Sometimes creational patterns are complementory: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.


Further readings


Popular Posts