Java Notes
Complete guide to Builder pattern — step-by-step construction, fluent interfaces, Director, telescoping constructor problem, and real-world Java implementations.
Intent
Separate the construction of a complex object from its representation, allowing the same construction process to create different representations.
The Problem: Telescoping Constructor
// ❌ Telescoping constructors — which parameter is which?
Pizza pizza = new Pizza("large", true, true, false, true, false, "thin", "tomato");
// What does the 4th boolean mean? Impossible to read!
// ❌ JavaBean pattern — allows invalid intermediate state
Pizza pizza = new Pizza();
pizza.setSize("large");
pizza.setCheese(true);
// Object is in invalid state between setters!
// Also mutable — not thread-safe
// ✅ Builder pattern — clear, immutable, validated
Pizza pizza = new Pizza.Builder("large")
.cheese(true)
.pepperoni(true)
.mushrooms(false)
.crust("thin")
.sauce("tomato")
.build();UML Structure
| │ + getResult() | Product │ |
| │ - product | Product │ |
| │ + getResult() | Product │ |
Builder with Director
// Director orchestrates building steps in a specific order
class ComputerDirector {
public Computer buildGamingPC() {
return new Computer.Builder("Intel i9-14900K", 64)
.storage(4096)
.gpu("NVIDIA RTX 4090")
.wifi(true)
.bluetooth(true)
.os("Windows 11")
.build();
}
public Computer buildDevelopmentPC() {
return new Computer.Builder("AMD Ryzen 9 7950X", 128)
.storage(2048)
.gpu("NVIDIA RTX 4070")
.wifi(true)
.os("Ubuntu 24.04")
.build();
}
public Computer buildBudgetPC() {
return new Computer.Builder("Intel i3-13100", 8)
.storage(256)
.wifi(true)
.os("Linux Mint")
.build();
}
}Real-World: HTTP Request Builder
Builder in Java Standard Library
// StringBuilder
String result = new StringBuilder()
.append("Hello")
.append(" ")
.append("World")
.toString();
// Stream.Builder
Stream<String> stream = Stream.<String>builder()
.add("a").add("b").add("c")
.build();
// Locale.Builder
Locale locale = new Locale.Builder()
.setLanguage("en")
.setRegion("US")
.build();
// ProcessBuilder
Process proc = new ProcessBuilder("ls", "-la")
.directory(new File("/tmp"))
.redirectErrorStream(true)
.start();Interview Questions
Q1: What problem does Builder solve?
Answer: It solves the telescoping constructor problem (too many constructor parameters) and the JavaBean problem (mutable, invalid intermediate state). Builder provides readable construction, immutability, and validation.
Q2: What is the difference between Builder and Factory patterns?
Answer: Factory creates objects in one step (focus on WHAT to create). Builder creates objects step-by-step (focus on HOW to create complex objects). Use Factory when creation is simple; Builder when the object has many optional parameters.
Q3: Why should the Builder be a static inner class?
Answer: (1) It has access to the outer class's private constructor, (2) It's logically part of the product, (3) Static means it doesn't need an enclosing instance, and (4) Usage reads naturally: new Product.Builder(...).
Q4: How does Builder ensure thread safety?
Answer: The built product is immutable (final fields, no setters). Even though the Builder itself is mutable during construction, the resulting object is thread-safe. Don't share Builder instances across threads.
Q5: Where is Builder pattern used in real-world Java?
Answer: StringBuilder, Stream.Builder, Locale.Builder, Calendar.Builder, Java HttpClient.newBuilder(), Spring UriComponentsBuilder, Lombok @Builder, Protocol Buffers.
Summary
In this chapter, we learned about Builder Design Pattern in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Builder Design Pattern.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, design, patterns, builder
Related Java Master Course Topics