The Builder Pattern

The Builder pattern is useful when we want to create objects with many properties to set and to ensure their immutability.
Let’s illustrate this concept. Lately, I have been cooking marinaded meat. But as you can imagine, it is far better to have all the ingredients mixed before marinading the meat.

We could simply use the constructor to do it, but it is lengthy, and possibly difficult to call if not all the ingredients are ready by the time we want to invoke the constructor.

public class Marinade {
  private Ingredient soySauce;
  private Ingredient garlic;
  private Ingredient gingembre;
  private Ingredient brownSugar;
  private Ingredient onion;

  public Marinade(Ingredient soySauce, Ingredient garlic, Ingredient gingembre, Ingredient brownSugar, Ingredient onion) {
    this.soySauce = soySauce;
    this.garlic = garlic;
    this.gingembre = gingembre;
    this.brownSugar = brownSugar;
    this.onion = onion;
  }
}

The other possbility is to use setters.

public class Marinade {
  private Ingredient soySauce;
  private Ingredient garlic;
  private Ingredient gingembre;
  private Ingredient brownSugar;
  private Ingredient onion;

  public Marinade() {
    this.soySauce = soySauce;
    this.garlic = garlic;
    this.gingembre = gingembre;
    this.brownSugar = brownSugar;
    this.onion = onion;
  }

  public void setSoySauce(Ingredient soySauce) {
    this.soySauce = soySauce;
  }

  public void setGarlic(Ingredient garlic) {
    this.garlic = garlic;
  }
  …
}

The problem with setters is that the properties are mutable. In our case, we do not want such a thing. Once our marinade is made, it is too late! Here comes the Builder Pattern.

public class Marinade {
  private final Ingredient soySauce;
  private final Ingredient garlic;
  private final Ingredient gingembre;
  private final Ingredient brownSugar;
  private final Ingredient onion;

  public Marinade(Builder builder) {
    this.soySauce = builder.soySauce;
    this.garlic = builder.garlic;
    …
  }

  public static class Builder() {
    private Ingredient soySauce;
    private Ingredient garlic;
    private Ingredient gingembre;
    private Ingredient brownSugar;
    private Ingredient onion;

    public Builder() {}

    public Marinade build() { 
     return new Marinade(this); 
    } 

   public void soySauce() { 
     this.soySauce = soySauce; 
   } 

   public void garlic() { 
     this.garlic = garlic; 
   } 
   ...
  }
}

In our case, the builder is an inner class. To build a marinade, we simply need:

// also called Fluent Builder/Interface since it returns itself making the construction "fluent"
Marinade marinade = new Marinade.Builder()
    .soySauce(soySauce) 
    .garlic(garlic)
    …
    .build();

Simple and elegant… and the properties are immutable.