前言

执行流程固定,但中间有些细节有细微差别。

代码示例

package com.template;

public abstract class Beverage {
    public final void create() {
        //烧水
        boilWater();
        //放主料
        pourInCup();
        //开始煮、泡
        brew();
        //辅料
        addCoundiments();
    }

    public abstract void addCoundiments();

    public void brew() {
        System.out.println("泡一泡");
    }

    public abstract void pourInCup();

    public void boilWater() {
        System.out.println("烧开水,烧到100°可以起锅了");
    }
}
package com.template;

public class Coffee extends Beverage {
    @Override
    public void addCoundiments() {
        System.out.println("放糖");
    }

    @Override
    public void pourInCup() {
        System.out.println("放入咖啡");

    }
}
package com.template;

public class Tea extends Beverage {
    @Override
    public void addCoundiments() {
        System.out.println("放..");
    }

    @Override
    public void pourInCup() {
        System.out.println("放入龙井茶");
    }
}
package com.template;

public class UnitTest {
    public static void main(String[] args) {
        Coffee coffee = new Coffee();
        coffee.create();

        Tea tea = new Tea();
        tea.create();
    }
}
烧开水,烧到100°可以起锅了
放入咖啡
泡一泡
放糖
------------------------------
烧开水,烧到100°可以起锅了
放入龙井茶
泡一泡
放..