Skip to content

Instantly share code, notes, and snippets.

@jillesvangurp
Created December 3, 2014 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jillesvangurp/8449359d7c065a16072e to your computer and use it in GitHub Desktop.
Save jillesvangurp/8449359d7c065a16072e to your computer and use it in GitHub Desktop.
Person builder
class Person {
// final fields can be public, no more getter bullshit
public final String name;
public final String sex;
public final int age;
...
// private constructor to be used by Builder only, constructor inject everything in one go and never modify.
private Person(String name, int age, String sex) {
this.name=name;
this.age=age;
this.sex=sex;
}
public static Person.Builder person() {
return new Builder();
}
// public static convenience method that gives you a builder with the name already set
public static Person.Builder person(String name) {
return new Builder().name(name).
}
// another convenience method
public static Person.Builder person(String name, int age, String sex) {
return new Builder().name(name).age(age).sex(sex);
}
public static class Builder() {
String name, sex;
int age;
....
// returns a properly immutable & 100% threadsafe Person object
public Person build() {
// construct the thing
return new Person(name,age,sex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment