Created
July 22, 2018 12:47
-
-
Save nhojpatrick/7e4a32918041d334a1fa19254d125efe to your computer and use it in GitHub Desktop.
Employee Builder example
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 Employee { | |
public static class Builder<T extends Employee> { | |
private T entity; | |
public Builder() { | |
this.entity = new Employee(); | |
} | |
public Builder withAge(final String age) { | |
this.entity.age = age; | |
return this; | |
} | |
public Builder withName(final String name) { | |
this.entity.name = name; | |
return this; | |
} | |
public Builder withRole(final String role) { | |
this.entity.role = role; | |
return this; | |
} | |
public T build() { | |
if (this.entity.age == null || this.entity.age.trim().isEmpty()) { | |
throw new IllegalArgumentException("Missing age"); | |
} | |
if (this.entity.name == null || this.entity.name.trim().isEmpty()) { | |
throw new IllegalArgumentException("Missing name"); | |
} | |
if (this.entity.role == null || this.entity.role.trim().isEmpty()) { | |
throw new IllegalArgumentException("Missing role"); | |
} | |
return new Employee(this); | |
} | |
} | |
private String age; | |
private String name; | |
private String role; | |
private Employee() { | |
} | |
private Employee(final Builder builder) { | |
this.age = builder.entity.age; | |
this.name = builder.entity.name; | |
this.role = builder.entity.role; | |
} | |
public String getAge() { | |
this.age; | |
} | |
public String getName() { | |
this.name; | |
} | |
public String getRole() { | |
this.role; | |
} | |
// equals not included in this example | |
// hashCode not included in this example | |
// toString not included in this example | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment