Design Pattern Download: The Builder Pattern

Matthew MacFarquhar
2 min readMar 8, 2022

The Builder pattern is a Creational Pattern used in software engineering when you want to create a complex object in steps, rather than with a constructor that does all the complex set-up steps at the time of creation. This avoids having constructors with fields that are usually null.

Example

Imaging we wanted to build a house, we want to be able to create a basic house, or houses with a pool and or garage. We could create a constructor with two boolean fields for hasGarage and hasPool. We would then need to pass in false for a majority of houses.

When to use the Builder?

  • When you have a class which has optional fields which are often left as null.
  • When you need to create a complex object which is comprised of simpler objects.

What is the Builder Pattern composed of?

  • The Builder interface (an interface outlining what the implementing concrete classes must be able to build)
  • The concrete Builders (the classes which implement the builder interface and create the desired end product)
  • The Director class(an class which is given an implementation of the builder to use)

Implementation

The Builder (Interface) 🧰

The general builder interface for the houses just say what a builder must be able to do.

The Concrete Builders 🏠🏰

These two builders both can build a regular house or a house with a garage and a pool, however different builders may build the final product in a different way (i.e. a garage vs a stable).

The Director 👨‍💼

The Director is given a builder and has methods to create a basic house, or take extra steps to create a more complex house, these multiple methods take the place of overloading the constructor for multiple parameters.

--

--

Matthew MacFarquhar

I am a software engineer working for Amazon living in SF/NYC.