Creational Design Pattern
Builder Design Pattern in Java
Construct complex objects step by step while keeping object creation readable, flexible, and safe.
In this lesson: The Builder pattern separates object construction from the final object. It is useful for many optional properties, readable creation, validation, and immutable objects.
Implementation
public final class User {
private final String name;
private final String email;
private User(Builder builder) {
this.name = builder.name;
this.email = builder.email;
}
public static Builder builder() { return new Builder(); }
public static final class Builder {
private String name;
private String email;
public Builder name(String name) { this.name = name; return this; }
public Builder email(String email) { this.email = email; return this; }
public User build() {
if (name == null || name.isBlank()) throw new IllegalStateException("Name is required");
return new User(this);
}
}
}
Example usage
User user = User.builder()
.name("Anand")
.email("anand@example.com")
.build();
When should you use it?
Use Builder when a class has many optional values or construction requires validation. It improves readability but adds a separate builder type.
Next step: Continue with the Design Patterns course.