Java23种设计模式-行为型模式之模板方法模式
//抽象类
public abstract class Beverage {
//模板方法
public final void perpareRecipe(){
boilwater();
brew();
pourInCup();
addCoundiments();
}
//基本方法,可以是抽象的,也可以为具体的
protected abstract void brew();
protected void addCoundiments(){
System.out.println("Adding lemon");
}
//钩子方法
protected void hood(){
System.out.println("Doing something before adding condiments");
}
//其他基本方法
private void boilwater(){
System.out.println("Boiling water");
}
private void pourInCup(){
System.out.println("Pouring into cup");
}
}
//具体类
public class Tea extends Beverage{
@Override
protected void brew() {
System.out.println("Steeping the tea");
}
public void addCondiments(){
super.addCoundiments();
System.out.println("Adding tea specific condiments");
}
}
//具体类
public class Coffee extends Beverage{
@Override
protected void brew() {
System.out.println("Dripping coffee through filter");
}
public void addCondiments(){
super.addCoundiments();
System.out.println("Adding coffee specific condiments");
}
public void hook(){
System.out.println("Doing somenthing coffee specific before adding condiments");
}
}
public class Client {
public static void main(String[] args) {
Beverage tea=new Tea();
tea.perpareRecipe();
System.out.println("----------------------------");
Beverage coffee=new Coffee();
coffee.perpareRecipe();
}
}