使用场景:
当内部处理逻辑是一样的,只是被调整的对象不同而已。
笨办法:
根据不同的类型,写多个实现的方法(重复代码会很多,维护起来不方便,有个地方要改动,所有的方法都要改动一次)
新方法:
定义实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Parent implements Serializable {
private String parentName;
private List<Son> sonList;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Son extends Parent implements Serializable {
private String name;
private int age;
}
实现:
public static void main(String[] args) {
Parent parent = new Parent();
parent.setParentName("张三");
List<Son> sonList = new ArrayList<>();
sonList.add(new Son("李四",12));
// 1:为父亲添加孩子
BiConsumer<Parent, List<Son>> consumer = (x,y) -> {
x.setSonList(y);
};
//setSonListInfo(parent, Parent::setSonList);
// 2:为父亲添加孩子,并更改父亲的名称
consumer.andThen((x,y) -> {
x.setSonList(y);
x.setParentName("张三三");
}).accept(parent,sonList);
System.out.println(parent.getParentName() + "-" +parent.getSonList());
Function<Parent,String> function = Parent::getParentName;
String s = function.apply(parent);
System.out.println(s);
}
public static<T> void setSonListInfo(T t, BiConsumer<T,List<Son>> setSonListInfo) {
List<Son> sonList = new ArrayList<>();
sonList.add(new Son("李四",12));
setSonListInfo.accept(t, sonList);
}