Builder Design Pattern

Intent

Builder - Intent

Divide the construction of multi-part objects in different steps, so that different implementations of these steps can construct different representations of objects.

Structure

Builder - Structure

DP Builder Structure

Builder defines the individual steps of the construction of Product.

Director knows in which order to construct Product.

ConcreteBuilder implements the steps of construction.

Example

We want to construct different types of cars.

In this example, cars have an engine and an interior.

Builder - A Car Builder

DP Builder ACar

Builder - A Car Builder

DP Builder CarBuilder

CarBuilder defines the two methods to construct car parts. Concrete builders must implement these methods. For convenience, the instantiation of cars (buildCar()) is implemented in CarBuilder.

CarConstructionDirector is configured with a CarBuilder and calls the construction methods in the correct order.

Two Possible Car Builders

class CheapCarBuilder extends CarBuilder {
  void buildEngine() {
    car.setEngine(Engine.SMALL_ENGINE);
  }

  void buildInterior() {
    car.setInterior(Interior.PLASTIC_INTERIOR);
  }
}
class LuxuryCarBuilder extends CarBuilder {
  void buildEngine() {
    car.setEngine(Engine.SPORT_ENGINE);
  }

  void buildInterior() {
    car.setInterior(Interior.WOODEN_INTERIOR);
  }
}

Discussion

Assessment of the Builder Pattern:

Builder vs. Abstract Factory Pattern:

Takeaway

Use Abstract Factory for creating objects depending on finite numbers of factors you know in advance.
E.g. if there are only three kinds of cars.

Use Builder for creating complex objects depending on unbound number of factors that are decided at runtime.
E.g. if cars can be configured with multiple different parts.