๐งฑ Builder Design Pattern in Java — Step-by-Step with Example
The Builder Pattern is a creational design pattern that provides a flexible solution for constructing complex objects step by step.
It’s especially useful when a class has many fields, and not all of them are required (some are optional).
Instead of passing dozens of constructor arguments (and remembering their order),
the Builder Pattern allows clean, readable object creation like this ๐
๐ฏ Why Builder Pattern?
Imagine you have a class with:
-
Mandatory fields (must always be provided)
-
Optional fields (can be skipped or defaulted to null)
If you use normal constructors, you might end up with “constructor telescoping”, like:
This is hard to read, hard to maintain, and error-prone.
The Builder Pattern fixes this problem by providing:
✅ Better readability
✅ Clear separation of mandatory & optional fields
✅ Immutable objects
✅ Easy object construction
⚙️ Example Use Case
We’ll create a Customer class where:
-
firstNameandlastNameare mandatory -
address,city, andzipCodeare optional
๐งฉ Step 1: Create the Customer Class
๐งช Step 2: Test the Builder Pattern
๐งพ Output
๐ง How It Works — Step by Step
| Step | Action | Explanation |
|---|---|---|
| 1️⃣ | Create a CustomerBuilder | Pass only mandatory fields to its constructor. |
| 2️⃣ | Chain setter methods | Use fluent syntax to set optional fields. |
| 3️⃣ | Call build() | Constructs a Customer by passing builder data to the private constructor. |
| 4️⃣ | Customer object is immutable | Because all fields are final and no setters exist in Customer. |
๐งญ When to Use the Builder Pattern
| Scenario | Why Builder Helps |
|---|---|
| Many parameters (some optional) | Avoids telescoping constructors |
| Object should be immutable | Builder handles initialization only once |
| Want readable, step-by-step object creation | Method chaining improves clarity |
| Need validation or defaults | Add checks inside build() |
⚡ Advantages
-
✅ Clean and readable object creation
-
✅ Avoids null handling for optional parameters
-
✅ Supports immutability
-
✅ Easy to extend without breaking existing code
-
✅ Works perfectly in Java 8 and above
๐ Summary
| Concept | Description |
|---|---|
| Pattern Type | Creational |
| Main Idea | Separate object construction from representation |
| Usage | When a class has multiple optional fields |
| Result | Cleaner, safer, and more maintainable code |
๐ฌ Real-World Analogy
Think of a pizza order ๐ —
You must choose the base (mandatory), but toppings like cheese, olives, or mushrooms are optional.
The Builder Pattern lets you create the exact “pizza” you want, without forcing you to specify every topping each time.
No comments:
Post a Comment