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

AspectDetails
PatternsBuilder, Step Builder, Factory Method, Abstract Factory
Use CasesComplex construction, many parameters, conditional creation
ToolsLombok @Builder, Records

šŸ”¬ Deep Dive

Pattern 1: Fluent Builder

JAVA(80 lines)
Code
Loading syntax highlighter...

Pattern 2: Step Builder (Compile-Time Safety)

JAVA(84 lines)
Code
Loading syntax highlighter...

Pattern 3: Static Factory Methods

JAVA(39 lines)
Code
Loading syntax highlighter...

Pattern 4: Factory with Spring

JAVA(35 lines)
Code
Loading syntax highlighter...

Lombok @Builder

JAVA(17 lines)
Code
Loading 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)
Code
Loading 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:
  1. baseBuilder.addItem(item2) - adds item2 to the list (now has item1, item2)
  2. baseBuilder.addItem(item3) - adds item3 to the SAME list (now has item1, item2, item3)
  3. Both order1 and order2 reference the same mutated list!
Fix 1: Defensive copy in build()
JAVA(3 lines)
Code
Loading syntax highlighter...
Fix 2: Immutable builder (each method returns new builder)
JAVA(8 lines)
Code
Loading 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)
Code
Loading syntax highlighter...
āœ… Solution:
JAVA(41 lines)
Code
Loading 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)
Code
Loading syntax highlighter...
āœ… Solution:
JAVA(42 lines)
Code
Loading syntax highlighter...

Exercise 3: Static Factory Methods

⭐⭐ Difficulty: Medium | ā±ļø Time: 15 minutes

Task: Replace constructors with static factory methods.
JAVA(9 lines)
Code
Loading syntax highlighter...
āœ… Solution:
JAVA(33 lines)
Code
Loading 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)
Code
Loading 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)
Code
Loading 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

PatternUse When
Fluent BuilderMany optional params, complex objects
Step BuilderRequired fields, compile-time safety
Static FactoryNamed construction, caching
Abstract FactoryFamily of related objects

šŸ“… Review Schedule for This Article

DayTaskTime
Day 1Review Builder vs Constructor decision table5 min
Day 3Redo Exercise 1 (Fluent Builder)15 min
Day 7Answer interview questions without looking10 min
Day 14Redo Debug This (Mutable Builder Trap)10 min
Day 30Find one constructor in your project that should be a builder15 min

Next: [Part 10: Composition Over Inheritance]