Java

Builder Pattern

https://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern (opens in a new tab)

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

Given

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

When

object is created over several calls it may be in an inconsistent state partway through its construction. This will cause thread safety issue.

Then

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;
 
  public static class Builder {
    //required
    private final int size;
 
    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;
 
    public Builder(int size) {
      this.size = size;
    }
 
    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }
 
    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }
 
    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }
 
    public Pizza build() {
      return new Pizza(this);
    }
  }
 
  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}