package com.test.design.template;
public abstract class CarModel {
//protected 对外不用暴露那么多方法
protected abstract void start();
protected abstract void stop();
protected abstract void engineBoom();
protected abstract void alarm();
//该方法为钩子方法(可以对run方法流程进行控制)
protected boolean isAlarm(){
return true;
}
public final void run(){
engineBoom();
start();
if(isAlarm()){
alarm();
}
stop();
}
}
package com.test.design.template;
public class BigCar extends CarModel {
private boolean alarmFlag = true;
@Override
protected void alarm() {
System.out.println("大车喇叭响了...");
}
@Override
protected void engineBoom() {
System.out.println("大车引擎启动了...");
}
@Override
protected void start() {
System.out.println("大车动起来了...");
}
@Override
protected void stop() {
System.out.println("大车停下来了...");
}
@Override
protected boolean isAlarm() {
return alarmFlag;
}
public void setAlarm(boolean isAlarm){
this.alarmFlag = isAlarm;
}
}
package com.test.design.template;
public class SmallCar extends CarModel {
@Override
protected void alarm() {
System.out.println("小车喇叭响了...");
}
@Override
protected void engineBoom() {
System.out.println("小车引擎启动了...");
}
@Override
protected void start() {
System.out.println("小车动起来了...");
}
@Override
protected void stop() {
System.out.println("小车停下来了...");
}
}
package com.test.design.template;
public class Client {
public static void main(String[] args) {
BigCar bigCar = new BigCar();
bigCar.setAlarm(false);
bigCar.run();
System.out.println("");
SmallCar smallCar = new SmallCar();
smallCar.run();
}
}
模板方法模式就是在模板方法中按照一个的规则和顺序调用基本方法,具体到上面那个例子就是run 方法按照规定的顺序调用本类的其他方法,并且由isAlarm 方法的返回值确定run 中的执行顺序变更