模板方法
泡咖啡为例
public abstract class RefreshBeverage {
/**
* 使用final关键字让子类无法更改固定流程
*/
public final void repareBeverageTemplate() {
boilWater();
brew();
/**
* 判断是否要加调料
*/
if (isCustomerWantsCondiments()) {
addCondiments();
}
pourInCup();
}
/**
* 使用钩子方法提高程序的灵活性
*/
protected boolean isCustomerWantsCondiments() {
return true;
}
private void pourInCup() {
System.out.println("倒入杯中");
}
private void boilWater() {
System.out.println("烧开水");
}
protected abstract void brew();
protected abstract void addCondiments();
}
public class Coffee extends RefreshBeverage {
@Override
protected void brew() {
System.out.println("泡制咖啡");
}
@Override
protected void addCondiments() {
System.out.println("添加糖");
}
/**
* 重写此方法表示不添加调料
*/
@Override
protected boolean isCustomerWantsCondiments() {
return false;
}
}
public class Test {
public static void main(String[] args) {
RefreshBeverage rb = new Coffee();
rb.repareBeverageTemplate();
}
}