何为“行为参数化”?
- 行为参数化:就是一个方法接受多个不同的行为作为参数,并在内部使用他们,完成不同行为的能力
为何要进行“行为参数化”?
- 应对频繁变更的需求以及繁琐的行为调用逻辑代码
“行为参数化”带来的优化是什么?
- 可以让代码更好的适应不断变化的需求,减轻未来的工作量
“行为参数化”有什么要求?
- 选择标准建模:对对象的某些属性来返回一个Boolean值,即我们把它称为一个谓词(一个返回Boolean值得函数)
“行为参数化”的实现方式?
- 普通方式实现
// 通过一个接口进行标准建模
public interface ApplePredicate{
Boolean test(Apple apple);
}
// 行为设定
public class AppleHeavyWeightPredicate implements ApplePredicate{
public Boolean test(Apple apple){
return apple.getWeight()>150;
}
}
public class AppleGreenColorWeightPredicate implements ApplePredicate{
public Boolean test(Apple apple){
return "green".equals(apple.getColor());
}
}
//行为/代码传递
public class List<Apple> filterApples(List<Apple> inventory,Predicate p){
List<Apple> result = new ArrayList<>();
for(Apple apple:inventory){
if(p.test(apple)){
result.add(apple);
}
}
return result;
}
- 使用匿名内部类
- 使用lambda表达式
List<Apple> result = filterApples(inventory,(Apple apple)->"red".equals(apple.getColor()));
- 将List类型抽象化(扩大方法使用的对象范围)
public interface Predicate<T>{
Boolean test(T t);
}
public class List<T> filterApples(List<T> inventory,Predicate<T> p){
List<Apple> result = new ArrayList<>();
for(T e:inventory){
if(p.test(e)){
result.add(e);
}
}
return result;
}