|
| 1 | +package example.builder; |
| 2 | + |
| 3 | +import org.apache.commons.lang3.builder.EqualsBuilder; |
| 4 | +import org.apache.commons.lang3.builder.HashCodeBuilder; |
| 5 | +import org.apache.commons.lang3.builder.ToStringBuilder; |
| 6 | + |
| 7 | +public class Person { |
| 8 | + |
| 9 | + private String firstName; |
| 10 | + private String middleName; |
| 11 | + private String lastName; |
| 12 | + private int age; |
| 13 | + |
| 14 | + // default constructor so the builder can create an empty version |
| 15 | + private Person() { |
| 16 | + } |
| 17 | + |
| 18 | + private Person(Person person) { |
| 19 | + this.firstName = person.getFirstName(); |
| 20 | + this.middleName = person.getMiddleName(); |
| 21 | + this.lastName = person.getLastName(); |
| 22 | + this.age = person.getAge(); |
| 23 | + } |
| 24 | + |
| 25 | + public String getFirstName() { |
| 26 | + return firstName; |
| 27 | + } |
| 28 | + |
| 29 | + public String getMiddleName() { |
| 30 | + return middleName; |
| 31 | + } |
| 32 | + |
| 33 | + public String getLastName() { |
| 34 | + return lastName; |
| 35 | + } |
| 36 | + |
| 37 | + public int getAge() { |
| 38 | + return age; |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public boolean equals(Object o) { |
| 43 | + return EqualsBuilder.reflectionEquals(this, o); |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public int hashCode() { |
| 48 | + return HashCodeBuilder.reflectionHashCode(this); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public String toString() { |
| 53 | + return ToStringBuilder.reflectionToString(this); |
| 54 | + } |
| 55 | + |
| 56 | + public static Builder getBuilder() { |
| 57 | + return new Builder(); |
| 58 | + } |
| 59 | + |
| 60 | + public static final class Builder { |
| 61 | + |
| 62 | + private final Person person = new Person(); |
| 63 | + |
| 64 | + public Builder firstName(String firstName) { |
| 65 | + this.person.firstName = firstName; |
| 66 | + return this; |
| 67 | + } |
| 68 | + |
| 69 | + public Builder middleName(String middleName) { |
| 70 | + this.person.middleName = middleName; |
| 71 | + return this; |
| 72 | + } |
| 73 | + |
| 74 | + public Builder lastName(String lastName) { |
| 75 | + this.person.lastName = lastName; |
| 76 | + return this; |
| 77 | + } |
| 78 | + |
| 79 | + public Builder age(int age) { |
| 80 | + this.person.age = age; |
| 81 | + return this; |
| 82 | + } |
| 83 | + |
| 84 | + public Builder name(Name name) { |
| 85 | + this.person.firstName = name.getFirstName(); |
| 86 | + this.person.middleName = name.getMiddleName(); |
| 87 | + this.person.lastName = name.getLastName(); |
| 88 | + return this; |
| 89 | + } |
| 90 | + |
| 91 | + //a new person is created here so that if a method in this instance of the Builder is called it will not change the value of the Person being returned. |
| 92 | + public Person build() { |
| 93 | + return new Person(person); |
| 94 | + } |
| 95 | + } |
| 96 | +} |
0 commit comments