25
17-214
A better solution: Use a Builder to hold build
instructions.
public class User {
private final String firstName;
private final String lastName;
private final int age;
private final String address;
private final String phone;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
…
}
public String getFirstName() { … }
public String getLastName() { … }
…
}
public static class Builder {
private final String firstName;
private final String lastName;
private int age;
private String address;
private String phone;
private UserBuilder(String firstName,
String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
…
}
new User.Builder(“Fred”, “Rogers”)
.age(30)
.phone(“1234567”)
.address(...)
.build();