传统的策略模式
public class TestMaxBy {
public static void main(String[] args) {
crossChannel(new Bird());
crossChannel(new FlyFish());
}
static void crossChannel(Fly fly){
System.out.println("开始过海峡");
fly.waveWings();
System.out.println("已经飞过海峡");
}
private interface Fly{
void waveWings();
}
private static class Bird implements Fly {
@Override
public void waveWings() {
System.out.println("wave wings once");
}
}
private static class FlyFish implements Fly {
@Override
public void waveWings() {
System.out.println("wave wings once");
System.out.println("rest, then another time");
}
}
}
使用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();
}
}