前言
Java 8 引入行为参数化,通俗来说是像一个动作/行为作为参数输入,这样可以对同一对象基于一套模版去实现不同动作/行为。
提示:以下是本篇文章正文内容,下面案例可供参考
一、行为参数化是什么?
行为参数化,帮助处理频繁变更的需求的一种软件开发模式,意味着拿出一个代码块,把它准备好却不去执行它。将代码块作为参数传递给另一个方法,稍后再去执行它。
二、演示示例
筛选苹果
要求:从苹果List中挑选满足条件的苹果,这些条件后续会不断变化
更高层次的抽象:根据 Apple 的某些属性,去返回一个 boolean 值,我们把它称为谓词
public interface ApplePredicate {
boolean test (Apple apple);
}
现在可以用 ApplePredicate 的多个实现代表不同的选择标准
和策略设计模式相关:定义一族算法(策略),封装起来,运行时候选择一个算法
public class AppleHeavyWeightPredicate implements ApplePredicate {
public boolean test(Apple apple) {
return apple.getWeight() > 150;
}
}
public class AppleGreenColorPredicate implements ApplePredicate {
public boolean test (Apple apple) {
return "green".equals(apple.getColor());
}
}
接下来是行为参数化的工作:让方法接收多种行为作为参数,并在内部使用,来完成不同的行为
public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate p) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if (p.test(apple)) {
result.add(apple);
}
}
return result;
}
总结
以上就是行为参数化的内容,本文仅仅简单介绍了行为参数化的定义与demo,重点是要将行为参数化的思想融于日常开发工作中,写出易于拓展的健康代码。
@北京·海淀 2020.12.03