HeadFirst设计模式-模板方法模式

 

模板方法模式:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。

 

 

package h_TemplateMethodPattern;

public abstract class CaffeineBeverage {
    
    final void prepareRecipe() {
        boilWater();
        brew();
        pourInCup();
        addCondiments();
    }
    
    abstract void brew();
    
    abstract void addCondiments();
    
    void boilWater() {
        System.out.println("Boiling water");
    }
    
    void pourInCup() {
        System.out.println("Pouring into cup");
    }

}
//----------------------
package h_TemplateMethodPattern;

public class Coffee extends CaffeineBeverage {

    @Override
    void brew() {
        System.out.println("Dripping Coffee through filter.");
    }

    @Override
    void addCondiments() {
        System.out.println("Adding Sugar and Milk");
    }

}
//----------------------
package h_TemplateMethodPattern;

public class Tea extends CaffeineBeverage {

    @Override
    void brew() {
        System.out.println("Stepping the tea");
    }

    @Override
    void addCondiments() {
        System.out.println("Adding Lemon");
    }

}

//----------------------
package h_TemplateMethodPattern;

public class TestDemo {
    
    public static void main(String[] args) {
        Tea tea = new Tea();
        tea.prepareRecipe();
        System.out.println("--------------------------");
        Coffee coffee = new Coffee();
        coffee.prepareRecipe();
    }

}
View Code

 

 

***

posted @ 2022-11-30 15:39  htj10  阅读(17)  评论(0编辑  收藏  举报
TOP