Created
December 3, 2014 15:22
-
-
Save jillesvangurp/8449359d7c065a16072e to your computer and use it in GitHub Desktop.
Person builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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