传统的策略模式
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();
}
}
本文通过两个具体示例展示了策略模式在Java中的应用:一个是传统策略模式的实现,使用了接口和具体类;另一个是利用Lambda表达式的现代策略模式实现。这两种方式都允许在运行时选择算法或行为。
3117

被折叠的 条评论
为什么被折叠?



