The criteria pattern
The criteria design pattern provides a clear and concise technique for filtering objects according to set criteria. It can be a very powerful tool as this next exercise will demonstrate.
In this example, we will apply a filter pattern to sort through a list of ingredients and filter them according to whether they are vegetarian and where they are produced:
- Begin by creating the filter interface, like so:
public interface Filter { List<Ingredient> meetCriteria(List<Ingredient> ingredients); }
- Next add the ingredient class, like this:
public class Ingredient { String name; String local; boolean vegetarian; public Ingredient(String name, String local, boolean vegetarian){ this.name = name; this.local = local; this.vegetarian = vegetarian; ...
Get Android Design Patterns and Best Practice now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.