Last active
November 29, 2016 15:26
-
-
Save 4e1e0603/4e294439e4a578ca85546cf9622f9775 to your computer and use it in GitHub Desktop.
Example of simple parametrized specification pattern implementation
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
/* | |
Specification Pattern | |
Simple use case: We have a person class with a birthdate attribute and we want to know if he is an adult. | |
The straigtforward approach is create the custom parametrized specification. | |
*/ | |
import java.time.Period; | |
import java.time.LocalDate; | |
public class FluentSpecificationExample { | |
public static void main(String[] args) { | |
BecomingAdultSpecification<Person> spec = | |
new BecomingAdultSpecification<Person>(18); | |
Person p1 = new Person(LocalDate.of(1990, 1, 1)); | |
Person p2 = new Person(LocalDate.of(2016, 1, 1)); | |
System.out.println(spec.isSatisfiedBy(p1)); | |
System.out.println(spec.isSatisfiedBy(p2)); | |
} | |
} | |
class Person { | |
private final LocalDate birthdate; | |
public Person(final LocalDate birthdate) { | |
// Check for `null` omitted. | |
this.birthdate = birthdate; | |
} | |
public LocalDate getBirthdate() { | |
return birthdate; | |
} | |
public int getAge() { | |
return Period.between(birthdate, LocalDate.now()).getYears(); | |
} | |
} | |
class BecomingAdultSpecification<T extends Person> { | |
public final int limit; | |
public BecomingAdultSpecification(int limit) { | |
assert(limit > 0); | |
this.limit = limit; | |
} | |
public boolean isSatisfiedBy(T candidate) { | |
return candidate.getAge() >= limit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment