public class User {
private final String firstName;
private final String lastName;
private final int age;
private final String email;
private final String phone;
// Private constructor
private User(Builder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.email = builder.email;
this.phone = builder.phone;
}
// Getters
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public int getAge() { return age; }
public String getEmail() { return email; }
public String getPhone() { return phone; }
// Builder class
public static class Builder {
private String firstName;
private String lastName;
private int age;
private String email;
private String phone;
// Required parameters
public Builder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Optional parameters with fluent interface
public Builder age(int age) {
this.age = age;
return this;
}
public Builder email(String email) {
this.email = email;
return this;
}
public Builder phone(String phone) {
this.phone = phone;
return this;
}
// Build method with validation
public User build() {
if (firstName == null || lastName == null) {
throw new IllegalStateException("First name and last name are required");
}
if (age < 0) {
throw new IllegalStateException("Age cannot be negative");
}
return new User(this);
}
}
}
// Generic builder interface
public interface Builder<T> {
T build();
}
// Advanced builder with validation
public class ProductBuilder implements Builder<Product> {
private String name;
private double price;
private String category;
public ProductBuilder name(String name) {
this.name = name;
return this;
}
public ProductBuilder price(double price) {
if (price < 0) {
throw new IllegalArgumentException("Price cannot be negative");
}
this.price = price;
return this;
}
public ProductBuilder category(String category) {
this.category = category;
return this;
}
@Override
public Product build() {
if (name == null) {
throw new IllegalStateException("Product name is required");
}
return new Product(name, price, category);
}
}