Instantly share code, notes, and snippets.

@DavW /Person.java Secret
Created Jan 13, 2016

Embed
What would you like to do?
Totally safe Builder
package radicaljava;
public class Person {
public final String firstName;
public final String lastName;
public final int age;
public final boolean vip;
public Person(String firstName, String lastName, int age, boolean vip) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.vip = vip;
}
public static ReqBuilder1 builder() {
return firstName -> lastName -> new OptBuilder(firstName, lastName);
}
public interface ReqBuilder1 { ReqBuilder2 setFirstName(String firstName); }
public interface ReqBuilder2 { OptBuilder setLastName(String lastName); }
public static class OptBuilder {
public final String firstName;
public final String lastName;
public int age = 21;
public boolean vip = false;
private OptBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public OptBuilder setAge(int age) {
this.age = age;
return this;
}
public OptBuilder setVip() {
this.vip = true;
return this;
}
public Person build() {
return new Person(firstName, lastName, 21, vip);
}
}
public static void usage() {
Person david = Person.builder().setFirstName("David").setLastName("Whiting").setVip().build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment