/**
* 类说明:抽象蛋糕模型
*/
public abstract class AbstractCake {
protected abstract void shape();
protected abstract void apply();
protected abstract void brake();
/*模板方法*/
// public final void run(){
// this.shape();
// this.apply();
// this.brake();
// }
/*模板方法*/
public final void run(){
this.shape();
//实际使用中保证灵活性,增加钩子
if(this.shouldApply()){
this.apply();
}
this.brake();
}
protected boolean shouldApply(){
return true;
}
}
/**
* 类说明:小蛋糕 继承实现抽象模板
*/
public class SmallCake extends AbstractCake {
private boolean flag = false;
public void setFlag(boolean shouldApply){
flag = shouldApply;
}
@Override
protected boolean shouldApply() {
return this.flag;
}
@Override
protected void shape() {
System.out.println("小蛋糕造型");
}
@Override
protected void apply() {
System.out.println("小蛋糕涂抹");
}
@Override
protected void brake() {
System.out.println("小蛋糕烘焙");
}
}
/**
* 类说明:生产蛋糕
*/
public class MakeCake {
public static void main(String[] args) {
//芝士蛋糕继承模板类
AbstractCake cake = new CheeseCake();
cake.run();
//小蛋糕继承模板类
AbstractCake smalCake = new SmallCake();
smalCake.run();
}
}