Skip to content

Instantly share code, notes, and snippets.

@vojtechruz
Created May 11, 2016 11:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vojtechruz/1ea4f51a016002bbdd0d493b049140dc to your computer and use it in GitHub Desktop.
Save vojtechruz/1ea4f51a016002bbdd0d493b049140dc to your computer and use it in GitHub Desktop.
Example of Builder as an inner static class. Enclosing class has private constructor, which prevents direct instantiation and allows creation only trough the uilder.
public class Person {
private final String firstName;
private final String lastName;
private final String description;
private final int age;
private Person(Builder builder) {
firstName = builder.firstName;
lastName = builder.lastName;
description = builder.description;
age = builder.age;
}
public static final class Builder {
private String firstName;
private String lastName;
private String description;
private int age;
public Builder() {
}
public Builder firstName(String val) {
firstName = val;
return this;
}
public Builder lastName(String val) {
lastName = val;
return this;
}
public Builder description(String val) {
description = val;
return this;
}
public Builder age(int val) {
age = val;
return this;
}
public Person build() {
return new Person(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment