Dwarves
Memo
Type ESC to close search bar

Introduce the Builder pattern and its use cases

Problem statement

We want to create complex object without worrying too much about the hows, we could use Factory pattern to abstract away those details and just give us the output, but the drawback is you get a fixed same object everytime. There will be cases where you need to tweak some properties of that object to get the desired result, look no further than the Builder pattern.

Builder design pattern

Create a Builder of the object you wanna build, e.g. QueryBuilder, ButtonBuilder, etc,…

Add methods that act as steps to gradually build your object, this method must return an instance of the builder itself to allow method chainning (not required but a very distinct feature of this pattern).

Have a method that finalizes and output the actual object, conventionally it’s called “build()”.

Let’s say we to build a Drink object, consider the following example of a DrinkBuilder class:

class DrinkBuilder implements Builder {
  private drink: Drink
  private name = ''
  private ingredients = []

  constructor() {}

  name(n: string) {
    this.name = n
    return this
  }

  addIngredient(name: string, ml: number) {
    this.ingredients.push({ name, ml })
    return this
  }

  // where the actual building happens
  mix() {
    return new Drink(this.name, this.ingredients)
  }
}

And then we can use it like this:

new DrinkBuilder()
    .name('JagerBomb')
    .addIngredient('Jagermeister', 30)
    .addIngredient('Redbull', 120).mix()

new DrinkBuilder()
    .name('JagerGrenade')
    .addIngredient('Jagermeister', 30)
    .addIngredient('Tequila', 30)
    .addIngredient('Vodka', 30)
    .addIngredient('Redbull', 50)
    .mix()

Notice how by defining each step as method we (the consumer, one that uses the builder) can easily add/skip/modify certain properties of the object, this would all have been hidden away by the Factory class. And the method chaining helps with the readability too.

Real life examples

jQuery was one of the early pioneers to adopt this pattern in their APIs, those little $(something).on("click", func).toggle("class")... is the Builder pattern in action. In fact, the javascript ecosytem is very fond of this pattern, some other libraries that make use of this are:

Pros & Cons

Pros:

Cons:

Reference