public interface ApplePredicate { /** * 谓词(选择标准) * @param apple * @return */ boolean test(Apple apple); }
public class AppleWeightPredicate implements ApplePredicate{ @Override public boolean test(Apple apple) { return apple.getWeight() > 150; } }
public class AppleGreenColorPredicate implements ApplePredicate{ @Override public boolean test(Apple apple) { return "green".equals(apple.getColor()); } }
public class FilterApples { /** * ApplePredicate参数实现了行为参数化 * @param inventory * @param p * @return */ public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate p) { List<Apple> result = new ArrayList<Apple>(); for (Apple apple : inventory) { if (p.test(apple)) { result.add(apple); } } return result; } /** * 匿名类实现 * @param inventory * @return */ public List<Apple> redApples(List<Apple> inventory) { return filterApples(inventory, new ApplePredicate() { @Override public boolean test(Apple apple) { return "red".equals(apple.getColor()); } }); } /** * 使用Lambda表达式 * @param inventory * @return */ public List<Apple> yellowApples(List<Apple> inventory) { return filterApples(inventory, (Apple apple) -> "yellow".equals(apple.getColor())); } }
List类型抽象化:
public interface CommonPredicate<T> { /** * 类型抽象化 * @param t * @return */ boolean test(T t); }
public class filter { /** * list类型抽象化 * @param list * @param p * @param <T> * @return */ public static <T> List<T> filter(List<T> list, CommonPredicate<T> p) { List<T> result = new ArrayList<T>(); for (T e : list) { if (p.test(e)) { result.add(e); } } return result; } public List<Apple> redApples(List<Apple> inventory) { return filter(inventory, (Apple apple) -> "red".equals(apple.getColor())); } public List<Integer> main(List<Integer> inventory) { return filter(inventory, (Integer i) -> i % 2 == 0); } }
行为参数化类似于策略设计模式。
原文地址:http://blog.51cto.com/turnsole/2093173