Builder Design Pattern in Java
Builder creates a big object step by step. You set only the parts you want, then call build().
Real life example
Ordering a pizza: you choose size, cheese and toppings one by one.
When to use
A class has many optional fields and a constructor with many parameters would be confusing.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
Pizza p = new Pizza.Builder().size("large").olives(true).build();
System.out.println(p); // large pizza, mozzarella cheese, olives: true
}
}
class Pizza {
private String size, cheese;
private boolean olives;
private Pizza(Builder b) { size = b.size; cheese = b.cheese; olives = b.olives; }
public String toString() { return size + " pizza, " + cheese + " cheese, olives: " + olives; }
static class Builder {
private String size = "medium", cheese = "mozzarella"; // default values
private boolean olives;
Builder size(String s) { size = s; return this; }
Builder cheese(String c) { cheese = c; return this; }
Builder olives(boolean o) { olives = o; return this; }
Pizza build() { return new Pizza(this); }
}
}Output
large pizza, mozzarella cheese, olives: true