Design Patterns

Builder



Design Pattern Type: Creational

GoF Statement of Intent:


Separates the construction of a complex object from its representation so that the same construction process can create different representations.
Brief Overview:



The intent is to "abstract" the steps of the construction of objects so that different implementations of these steps can construct different representations of objects. The builder is often used to build products that are following the Composite Design Pattern which is a structural pattern.
UML Diagram:

Discussion and In-class Example:

Suppose you are developing a vacation planner application. This application you must be able to create tree structures like that in the image below in a step-wise fashion. Everything in the tree can vary; number of days, activities, etc.
You need:
  1. A flexible data structure.
  2. To be able to follow a possibly complex series of steps to create the tree.
  3. To be able to create the tree structure without mixing it with the steps for creating its components.
In this example we encapsulate the creation of a trip planner structure in an object called a builder. The client then just asks the builder to construct the vacation planner for it.

Advantages of using a Builder
  1. Encapsulates the way a complex object is constructed.
  2. Allows objects to be constructed in a multi-step and varying process as opposed to the one-step method of factories.
  3. Hides the internal representation of the product (our vacation plan) from the client.
  4. Product implementation can be swapped in and out because the client only sees an abstract interface.