传统模板模式的写法,用匿名类:
public class TestMaxBy {
public static void main(String[] args) {
crossChannel(new Fly() {
public void waveWings() {
System.out.println("wave wings once");
}
}
);
crossChannel(new Fly() {
public void waveWings() {
System.out.println("wave wings once");
System.out.println("rest, then another time");
}
}
);
}
static void crossChannel(Fly fly){
System.out.println("开始过海峡");
fly.waveWings();
System.out.println("已经飞过海峡");
}
private interface Fly{
void waveWings();
}
}
使用lambda简化后的模板模式:
public class TestMaxBy {
public static void main(String[] args) {
crossChannel(() -> System.out.println("wave wings once"));
crossChannel(() -> {System.out.println("wave wings once");
System.out.println("rest, then another time");});
}
static void crossChannel(Fly fly){
System.out.println("开始过海峡");
fly.waveWings();
System.out.println("已经飞过海峡");
}
private interface Fly{
void waveWings();
}
}