1. Core Concepts
The Builder Pattern is a Creational Design Pattern (a pattern about how objects get created). It builds a complex object step by step.
Why use it?
- Eliminates Telescoping Constructors: You do not need 10 constructors for different combinations of fields.
- Readable Code: Using
.withCheese(true)is much clearer than just passingtruein a long list of arguments. - Controlled Construction: You can check the data before the object is created.
2. Java Specifics Used
private final Fields
By making the fields in the main class final, we get Immutability (the object cannot change after it is built). Once build() is called, the BurgerMeal is fixed. This is also thread-safe, because several threads can read it and none can change it.
static Nested Class
The Builder is inside the BurgerMeal class and marked as static.
- Static: Lets us call
new BurgerMeal.BurgerMealWithBuilder("wheat", "non-veg")without aBurgerMealobject first. - Nested: Keeps the builder next to the class it builds, so the code is easy to find.
private Constructor
The constructor of the main class is private. This forces developers to use the Builder, so no "half-finished" or "invalid" object is created by hand.
return this; (Fluent Interface)
Each optional method returns the builder itself. This allows Method Chaining: calls written one after another, so the code reads like a sentence.
3. Comparison
| Feature | Telescoping (Bad) | Builder (Good) |
|---|---|---|
| Optional Params | Requires null or multiple constructors | Just skip the method call |
| Readability | Hard to tell what each value does | Explicit method names (e.g., withSide) |
| Immutability | Hard to achieve with many params | Easily achieved with final fields |