23种设计模式之很好理解的模板模式

时间:2022-12-10 20:14:28
public abstract class RefreshBeverage {
    /*
    final 阻止子类对父类的重写
     */
    public final void prepareBeverageTemplate(){
        boilWater();
        brew();
        pourInCop();
        addCondiments();
    }

    private void boilWater(){
        System.out.println("step one:boil....");
    }

    protected abstract void brew();

    private void pourInCop(){
        System.out.println("step three pour...");
    }

    protected abstract void addCondiments();
}
public class Coffee extends RefreshBeverage {
    @Override
    protected void brew() {
        System.out.println("step two coffee brew...");
    }

    @Override
    protected void addCondiments() {
        System.out.println("step four add coffee...");
    }
}
public class Tea extends RefreshBeverage {
    @Override
    protected void brew() {
        System.out.println("step two tea....");
    }

    @Override
    protected void addCondiments() {
        System.out.println("step four add tee...");
    }
}
public class testMain {
    public static void main(String[] args) {
        RefreshBeverage coffee=new Coffee();
        coffee.prepareBeverageTemplate();
        RefreshBeverage tea=new Tea();
        tea.prepareBeverageTemplate();
    }
}

添加钩子函数,让程序更灵活

public abstract class RefreshBeverage {
    /*
    final 阻止子类对父类的重写
     */
    public final void prepareBeverageTemplate(){
        boilWater();
        brew();
        pourInCop();
        if(isCustomerWantsCondiments()){
            addCondiments();
        }
    }

    /**
     * 询问用户是否加入调料 钩子函数,
     * 提供一个默认或空的实现 具体的子类可以自行决定是否挂钩以及如何挂钩
     * @return
     */
    protected boolean isCustomerWantsCondiments(){
        return true;
    }

    private void boilWater(){
        System.out.println("step one:boil....");
    }

    protected abstract void brew();

    private void pourInCop(){
        System.out.println("step three pour...");
    }

    protected abstract void addCondiments();
}