The Builder Pattern is a creational design pattern that separates the construction of a complex object from its representation. It allows you to construct objects step-by-step using a fluent interface, making the code more readable and maintainable.
- Complexity Management: When an object has many optional parameters and configurations
- Readability: Method chaining makes code more readable and self-documenting
- Flexibility: Easily create different variations of complex objects
- Immutability: Build immutable objects safely
- Reduced Constructor Overloading: Avoids telescoping constructors (multiple overloaded constructors)
// WITHOUT Builder Pattern - Difficult to read and maintain
Computer c = new Computer("Intel i9", "Z590", "32GB", "RTX 3080", "1TB SSD", true, false);
// What does each parameter mean? Order matters!
// WITH Builder Pattern - Clear and maintainable
Computer c = new Computer.Builder("Intel i9", "Z590")
.withRam("32GB")
.withGpu("RTX 3080")
.withStorage("1TB SSD")
.build();Objects built with the Builder pattern are immutable once created, preventing accidental modifications.
The builder can validate the final object before creation, ensuring consistency.
- Builder Class: Responsible only for constructing the object
- Product Class: Responsible only for representing the data
- Easy to extend with new builder methods without modifying existing code
- Client depends on the abstract Builder interface, not concrete implementations
// Messy and error-prone
public class Computer {
public Computer(String cpu, String motherboard, String ram,
String gpu, String storage, boolean hasWifi) {
this.cpu = cpu;
this.motherboard = motherboard;
this.ram = ram;
this.gpu = gpu;
this.storage = storage;
this.hasWifi = hasWifi;
}
// Too many overloaded constructors for different combinations
public Computer(String cpu, String motherboard) { ... }
public Computer(String cpu, String motherboard, String ram) { ... }
public Computer(String cpu, String motherboard, String ram, String gpu) { ... }
// And many more...
}
// Usage - Confusing!
Computer c = new Computer("Intel i9", "Z590", "32GB", "RTX 3080", "1TB", true);Computer gaming = new Computer.Builder("Intel i9", "Z590")
.withRam("32GB")
.withGpu("RTX 3080")
.withStorage("1TB SSD")
.build();✓ Fluent Interface: Method chaining for cleaner code ✓ Step-by-step Construction: Build complex objects gradually ✓ Default Values: Optional parameters with sensible defaults ✓ Immutability: Resulting objects are immutable ✓ Validation: Validate the complete object before creation
- Creating complex configuration objects
- Building objects with many optional parameters
- Creating immutable objects
- Creating objects that require validation
- SQL query builders, HTTP request builders, etc.
FluentBuilder.java- Pizza builder exampleComputerBuilder.java- Computer configuration builderDocumentBuilder.java- Document construction builder