java vuser 参数化,java8之行为参数化(一)

public static List filterGreenApples(List inventory){

List result = new ArrayList<>();

for (Apple apple: inventory){

if ("green".equals(apple.getColor())) {

result.add(apple);

}

}

return result;

}

public static List filterHeavyApples(List inventory){

List result = new ArrayList<>();

for (Apple apple: inventory){

if (apple.getWeight() > 150) {

result.add(apple);

}

}

return result;

}那么,现在丙、丁又分别提出了从苹果选取产自郑州、品种为红富士的需求,怎么办呢,继续写函数?如果又加了无尽的需求呢?是不是不利于代码的扩展性呢?那么以前人们在遇到这个问题时是怎么处理的呢?没错,用的就是策略模式,即设计一个接口,将接口的不同实现类的实例传入方法内,而这个接口就称为断言。具体看实例吧:interface ApplePredicate{

public boolean test(Apple a);

}

static classAppleWeightPredicate implementsApplePredicate{

public booleantest(Apple apple){

returnapple.getWeight() > 150;}

}

static classAppleColorPredicate implementsApplePredicate{

public booleantest(Apple apple){

return"green".equals(apple.getColor());}

}

public staticList filter(List inventory,ApplePredicate p){

List result = newArrayList<>();for(Apple apple : inventory){

if(p.test(apple)){

result.add(apple);}

}

returnresult;}

使用的方法如下:

// [Apple{color="green", weight=80}, Apple{color="green", weight=155}]List greenApples2 = filter(inventory, newAppleColorPredicate());System.out.println(greenApples2);// [Apple{color="green", weight=155}]List heavyApples = filter(inventory, newAppleWeightPredicate());System.out.println(heavyApples);怎么样,是不是将不同的部分抽象出来会使代码读起来更清晰,也更容易维护呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值