GoF Design Patterns – Builder Design Pattern


The Builder Design Pattern is a creational design pattern that allows creating complex objects using the same construction process and provides the flexibility of choosing attribute values with which object should be created. It allows creating complex objects in a step-by-step manner. It provides a way to separate the construction logic of an object from its representation, allowing for the creation of different variations of the same object using a common construction process. This pattern is particularly useful when dealing with complex objects that require multiple steps to be completed in a specific order, and when the construction process needs to be flexible and extensible.

This pattern is especially useful when you observe the following code smells:

  • long constructors
public class TravelItinerary {
    // ...

    public TravelItinerary(flights, hotels, transportation, activities, meals, ...) {
        // ...

  • calls to constructs with null arguments
new TravelItinerary(flights: "JFK-LAX", hotels: null, transportation: "car", activities: null, meals: null);

  • a complex hierarchy of classes that could be avoided by generalizing class and using it in different variations by separating a construction process

The Builder Design Pattern allows you to avoid the above code smells by introducing a Director that orchestrates a Builder that is used in the following way:

new TravelItinerary.Builder()

More on this pattern…

To read more on this and the other patterns, get “GoF Design Patterns Distilled” book from Amazon or Leanpub: