用lambda簡化模板模式 template method

傳統模板模式的寫法,用匿名類:

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();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章