Builder Pattern

Builder Pattern

Builder pattern separates the construction of complex object from its representation

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

Motivation

Consider an application which contains a complex object, with many specifications. Some of these specifications are optional and some mandatory. Keeping the different implementations of the construction process within the object will make the it less modular. And adding a new implementation requires change in the existing code-base.

The Builder pattern solves this problem by moving the object construction logic out of the object and into a builder class.

Applicability

The Builder pattern can be used in cases where:

  • Construction of an object must enable different representations of the object
  • Telescopic Constructor are to be avoided

Structure

Builder pattern class diagram

Participants

  • Builder: Abstract interface for creating parts of Product object
  • ConcreteBuilder: Construct, assemble parts of Product
  • Director: Construct object using Builder
  • Product: Representation of the complex object under construction

Collaborations

  • Director is configured with a Builder object
  • One way communication between Director and Builder.
  • Director notifies Builder which part should be built, then Builder handles the request.

Advantages

  • isolates code for construction and representation
  • help avoid telescopic constructor
  • more control over the construction process

Disadvantages

  • Increased complexity in code due to increase in new interfaces and classes

Implementation

In most cases one builder instance is enough so builders are implemented as singletons.

Demo

There are different variety of cakes served at the cafe. Even though all of them are cakes, they all have different ingredients. The owners want an optimized way of making the cakes, that will save the chef's time and also easily add new cake types to the menu in the future.

To solve this problem, we create a Cake class with all the required attributes. Then we create an abstract CakeBuilder class, which has abstract methods for building each component of the cake. We then extend this class to make concrete classes for the different variety of cakes. Lastly, we create a Chef class that will use one of this concrete classes to make the cake and return the created object.