Small variation of the blog post https://javatechnicalwealth.com/blog/2018/04/16/cascading-lambdas-and-builder-pattern-in-java-when-1-1-3-but-not-4/ when keeping Person and PersonBuilder in separate classes. The Person class is really just a data class here, but constructor needs to be package scoped instead of being declared private
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; | |
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); | |
} | |
} |
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; | |
public class PersonBuilder { | |
private final String firstName; | |
private final String lastName; | |
private LocalDate dateOfBirth; | |
private PersonBuilder(String firstName, String lastName) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
} | |
public PersonBuilder dateOfBirth(LocalDate birthday) { | |
this.dateOfBirth = birthday; | |
return this; | |
} | |
public Person build() { | |
return new Person(firstName, lastName, 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment