版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyaya8/article/details/85158176
函数式编程
在很多语言中,函数式一等公民,比如Golang,Python,Scala,但是在java8之前,java一直是值是一等公民,想要传递一个行为或者一个方法给另外一个方法,必须要将这个方法包装在一个类中,如果这样要传递多个行为,代码将会爆炸。。。
实体类:
package com.tangdandan.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@AllArgsConstructor
public class Apple {
private int weight = 0;
private String color = "";
}
查询第一版
根据颜色查询:
private ArrayList<Apple> filterApplesWithColor(ArrayList<Apple> appleArrayList, String color) {
ArrayList<Apple> apples = new ArrayList<>();
for (Apple greenApple : appleArrayList) {
if (color.equals(greenApple.getColor())) {
apples.add(greenApple);
}
}
return apples;
}
根据重量筛选:
private ArrayList<Apple> filterApplesWithWeight(ArrayList<Apple> appleArrayList, int weight) {
ArrayList<Apple> apples = new ArrayList<>();
for (Apple greenApple : appleArrayList) {
if (greenApple.getWeight() > weight) {
apples.add(greenApple);
}
}
return apples;
}
上述代码可以得到我们想要的结果,但是某天需求变了,要根据Apple的category来筛选,又得写一遍上述的代码?
查询第二版
我们可以用设计模式,将多余的代码抽取出来
定义策略接口
这个接口应该抽象出是否应该将满足条件的苹果筛选出来
public interface ApplePredict{
boolean test(Apple apple);
}
根据颜色来筛选苹果实现类:
public class ColorApplePredict implement {
@Override
public boolean test(Apple apple) {
if("green".equals(apple.getColor()){
return apple;
}
}
}
根据重量来筛选苹果实现类:
public class WeightApplePredict implement {
@Override
public boolean test(Apple apple) {
if(apple.getWeight()>150){
return apple;
}
}
}
测试类:
public class MainTest{
@Test
public void fun() {
//根据不同的策略筛选苹果,将行为作为参数传递给方法
filterApples(inventory, new WeightApplePredict());
}
}
符合设计模式中的开闭原则。但是不同的策略还是需要一个实现类来承载,能不能跳过类,直接将行为传递给方法呢?
用Lambda来简化行为的传递
public class MainTest{
@Test
public void filterGreenApples() {
//筛选绿色的苹果:
filterApples(inventory, (Apple apple)->"green".equals(apple.getColor()));
}
@Test
public void filterGreenApples() {
//筛选重量大于150g的苹果:
filterApples(inventory, (Apple apple)->apple.getWeight()>150);
}
}
由此可见,lambda帮我们省去了多余的代码,将不同的策略的核心代码直接在方法上传递;