public class User {
private final String name;
private final String email;
private final int age;
private final String phone;
private User(Builder builder) {
this.name = builder.name;
this.email = builder.email;
this.age = builder.age;
this.phone = builder.phone;
}
public static class Builder {
private String name;
private String email;
private int age;
private String phone;
public Builder name(String name) {
this.name = name; return this;
}
public Builder email(String email) {
this.email = email; return this;
}
public Builder age(int age) {
this.age = age; return this;
}
public Builder phone(String phone) {
this.phone = phone; return this;
}
public User build() {
return new User(this);
}
}
public static void main(String[] args) {
User user = new User.Builder()
.name("Alice")
.email("alice@example.com")
.age(30)
.build();
}
}The Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations. It is particularly useful when an object requires many optional parameters or when the construction process involves multiple steps. Instead of using telescoping constructors, the Builder pattern provides a fluent API that makes code more readable and maintainable.