呱呱8-1-行为参数化

何为“行为参数化”?

  1. 行为参数化:就是一个方法接受多个不同的行为作为参数,并在内部使用他们,完成不同行为的能力

为何要进行“行为参数化”?

  1. 应对频繁变更的需求以及繁琐的行为调用逻辑代码

“行为参数化”带来的优化是什么?

  1. 可以让代码更好的适应不断变化的需求,减轻未来的工作量

“行为参数化”有什么要求?

  1. 选择标准建模:对对象的某些属性来返回一个Boolean值,即我们把它称为一个谓词(一个返回Boolean值得函数)

“行为参数化”的实现方式?

  1. 普通方式实现
// 通过一个接口进行标准建模
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;
}
  1. 使用匿名内部类
  2. 使用lambda表达式
List<Apple> result = filterApples(inventory,(Apple apple)->"red".equals(apple.getColor()));
  1. 将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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

booth-ZDH

爪哇一生

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值