Explain the Builder pattern and when to use it.
Topic: design-patterns, Creational Patterns. Level: Intermediate.
Answer
Builder constructs a complex object step by step, separating construction from representation. It's ideal when a class has **many (especially optional) parameters** — avoiding the "telescoping constructor" anti-pattern and confusing positional args. The builder exposes fluent, named setters and a `build()` that returns an immutable object, and can validate invariants before construction. Use it for objects with many optional fields or that must be immutable.
```java
class Pizza {
private final int size; private final boolean cheese, pepperoni, mushroom;
private Pizza(Builder b){ size=b.size; cheese=b.cheese; pepperoni=b.pepperoni; mushroom=b.mushroom; }
static class Builder {
private final int size; // required
private boolean cheese, pepperoni, mushroom; // optional
Builder(int size){ this.size = size; }
Builder cheese(boolean v){ this.cheese=v; return this; } // fluent
Builder pepperoni(boolean v){ this.pepperoni=v; return this; }
Builder mushroom(boolean v){ this.mushroom=v; return this; }
Pizza build(){
if (size <= 0) throw new IllegalStateException("bad size"); // validate
return new Pizza(this);
}
}
}
Pizza p = new Pizza.Builder(12).cheese(true).mushroom(true).build();
```