Final version of Person.java from the blog post https://javatechnicalwealth.com/blog/2018/04/16/cascading-lambdas-and-builder-pattern-in-java-when-1-1-3-but-not-4/
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
import java.time.LocalDate; | |
import java.util.Optional; | |
import static java.util.Objects.requireNonNull; | |
public final class Person { | |
private final String firstName; | |
private final String lastName; | |
private final LocalDate dateOfBirth; | |
private Person(String firstName, String lastName, LocalDate dateOfBirth) { | |
this.firstName = requireNonNull(firstName, "firstName cannot be null"); | |
this.lastName = requireNonNull(lastName, "lastName cannot be null"); | |
this.dateOfBirth = dateOfBirth; | |
} | |
public String getFirstName() { | |
return firstName; | |
} | |
public String getLastName() { | |
return lastName; | |
} | |
public Optional<LocalDate> getDateOfBirth() { | |
return Optional.ofNullable(dateOfBirth); | |
} | |
@FunctionalInterface | |
public interface FirstNameBuilder { | |
LastNameBuilder firstName(String firstName); | |
} | |
@FunctionalInterface | |
public interface LastNameBuilder { | |
PersonBuilder lastName(String lastName); | |
} | |
public static FirstNameBuilder builder() { | |
return firstName -> lastName -> new PersonBuilder(firstName, lastName); | |
} | |
public static class PersonBuilder { | |
private final String firstName; | |
private final String lastName; | |
private LocalDate dateOfBirth; | |
private PersonBuilder(String firstName, String lastName) { | |
this.firstName = requireNonNull(firstName); | |
this.lastName = requireNonNull(lastName); | |
} | |
public PersonBuilder dateOfBirth(LocalDate birthday) { | |
this.dateOfBirth = birthday; | |
return this; | |
} | |
public Person build() { | |
return new Person(firstName, lastName, dateOfBirth); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment