Created
May 11, 2016 11:38
-
-
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.
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
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