Implement boolean logic to check whether objects meet certain requirements.
Use this in the following cases :
- You want to test objects by multiple criteria using boolean logic.
- You need to be able to combine the criteria.
- You do not have access to the implementation of the objects you want to test.
Note : In these situations, you cannot implement the criteria by hand because of the combination factor that would create an explosion of classes.
Participants
- ISpecification : Templated Interface that declares the isSatisfiedBy(T) method.
- CompositeSpecification : Composite nodes for the AND, OR and NOT operators.
- ConcreteSpecification : Leaf elements for the various kind of tests that can be composed.
Note : UML class diagram taken from here
Pros
- Opened/Closed principle: It is easy to introduce new conditions and tests without duplicating code.
- Very flexible : Possibility of combining criterias to perform various tests without many specialized classes.
- Logic : Supports logical operations, which produces easy-to-read code.
Cons
- Complex : Must invest in complex framework.
- An article by Eric Evans and Martin Fowler
- An complete article illustrating the use of the pattern.
