Java
Builder and Factory Patterns
When object creation becomes complex, Builder and Factory patterns provide clean solutions. This article covers fluent builders, step builders, static factory methods, and Spring integration.
📋 At a Glance
| Aspect | Details |
|---|---|
| Patterns | Builder, Step Builder, Factory Method, Abstract Factory |
| Use Cases | Complex construction, many parameters, conditional creation |
| Tools | Lombok @Builder, Records |
🔬 Deep Dive
Pattern 1: Fluent Builder
JAVA(80 lines)CodeLoading syntax highlighter...
Pattern 2: Step Builder (Compile-Time Safety)
JAVA(84 lines)CodeLoading syntax highlighter...
Pattern 3: Static Factory Methods
JAVA(39 lines)CodeLoading syntax highlighter...
Pattern 4: Factory with Spring
JAVA(35 lines)CodeLoading syntax highlighter...
Lombok @Builder
JAVA(17 lines)CodeLoading syntax highlighter...
🐛 Debug This: The Mutable Builder Trap
A developer reports: "We're getting random test failures. The same builder creates different objects in different tests!"
JAVA(35 lines)CodeLoading syntax highlighter...
Why do orders have different items? Find the state mutation bug!
✅ Solution:
The builder is mutable and reused - each
addItem() call modifies the shared items list:baseBuilder.addItem(item2)- adds item2 to the list (now has item1, item2)baseBuilder.addItem(item3)- adds item3 to the SAME list (now has item1, item2, item3)- Both
order1andorder2reference the same mutated list!
Fix 1: Defensive copy in build()
JAVA(3 lines)CodeLoading syntax highlighter...
Fix 2: Immutable builder (each method returns new builder)
JAVA(8 lines)CodeLoading syntax highlighter...
The lesson: Builders should either be single-use or return new instances on modification. Mutable shared state causes subtle bugs.
💻 Exercises
Exercise 1: Implement Fluent Builder
⭐ Difficulty: Easy | ⏱️ Time: 15 minutes
Task: Create a fluent builder for this class.
JAVA(9 lines)CodeLoading syntax highlighter...
✅ Solution:
JAVA(41 lines)CodeLoading syntax highlighter...
Exercise 2: Step Builder Pattern
⭐⭐ Difficulty: Medium | ⏱️ Time: 20 minutes
Task: Create a step builder that enforces: customerId → items → build.
JAVA(6 lines)CodeLoading syntax highlighter...
✅ Solution:
JAVA(42 lines)CodeLoading syntax highlighter...
Exercise 3: Static Factory Methods
⭐⭐ Difficulty: Medium | ⏱️ Time: 15 minutes
Task: Replace constructors with static factory methods.
JAVA(9 lines)CodeLoading syntax highlighter...
✅ Solution:
JAVA(33 lines)CodeLoading syntax highlighter...
Exercise 4: Abstract Factory
⭐⭐⭐ Difficulty: Medium-Hard | ⏱️ Time: 20 minutes
Task: Create an Abstract Factory for UI components that supports different themes.
✅ Solution:
JAVA(34 lines)CodeLoading syntax highlighter...
Exercise 5: Lombok @Builder with Validation
⭐⭐⭐⭐ Difficulty: Hard | ⏱️ Time: 25 minutes
Task: Create a Lombok builder with custom validation and defaults.
✅ Solution:
JAVA(40 lines)CodeLoading syntax highlighter...
🎤 Senior-Level Interview Questions
Q1: Builder vs Constructor - when to use each?
A:
- Constructor: 1-3 required parameters, all simple types
- Builder: 4+ parameters, optional parameters, complex objects
- Rule of thumb: If you need to look at JavaDoc to understand parameter order, use Builder
Q2: How do you make builders thread-safe?
A:
- Return new builder instance from each method (immutable builder)
- Or make builder single-use and not shared
- Or synchronize access (rarely needed)
Q3: What's the difference between Static Factory and Factory Method pattern?
A:
- Static Factory: Static method that returns instance (
Money.of(100, USD)) - Factory Method: Abstract method overridden by subclasses to create objects
- Static Factory is about naming and caching, Factory Method is about polymorphic creation
📝 Summary
| Pattern | Use When |
|---|---|
| Fluent Builder | Many optional params, complex objects |
| Step Builder | Required fields, compile-time safety |
| Static Factory | Named construction, caching |
| Abstract Factory | Family of related objects |
📅 Review Schedule for This Article
| Day | Task | Time |
|---|---|---|
| Day 1 | Review Builder vs Constructor decision table | 5 min |
| Day 3 | Redo Exercise 1 (Fluent Builder) | 15 min |
| Day 7 | Answer interview questions without looking | 10 min |
| Day 14 | Redo Debug This (Mutable Builder Trap) | 10 min |
| Day 30 | Find one constructor in your project that should be a builder | 15 min |
Next: [Part 10: Composition Over Inheritance]