Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

Latest commit

 

History

History
47 lines (36 loc) · 1.08 KB

item-02.md

File metadata and controls

47 lines (36 loc) · 1.08 KB

Item 02: Consider a builder when faced with many constructor parameters

Builder pattern

  • Good for designing classes whose constructors or static factories would have more than a handful of parameters.
  • Better to start with a builder in the first place to avoid obsolete constructors or static factories.
public class NutritionFacts {
  public static class Builder {
    // required parameters
    // ...
    
    // optional parameters - initialized to default values
    // ...

    // builder methods
    public NutritionFacts build() {
      return new NutritionFacts(this);
    }
  }
  
  // builder constructor
  private NutritionFacts(Builder builder) {
    // set up parameters
  }
}

Builder for class hierarchies

Simulated self-type idiom: the self() method provides a workaround for the fact that Java lacks a self type.

public abstract class Pizza {
  abstract static class Builder<T extends Builder<T>> {
    abstract Pizza build();

    // self-type idiom
    protected abstract T self();
  }
  
  Pizza(Builder<?> builder) {
    // set up parameters
  }
}