HummerModel.java代码如下:
HummerH1Model.java代码如下:
HummerH2Model.java代码如下:
Client.java代码如下:
运行结果如下:
package com.designPattern.templateMethod;
public abstract class HummerModel {
protected abstract void start();
protected abstract void stop();
protected abstract void alarm();
protected abstract void engineBoom();
/**
* 这就是模板方法:run()定义了其他方法的顺序,并且子类不能修改这个run()方法(修饰符为final)
* 在模板方法中按照一定的规则和顺序调用抽象方法,抽象方法在不同的子类中内容不同
*/
final public void run(){
this.start();
this.engineBoom();
if(this.isAlarm()){
this.alarm();
}
this.stop();
}
protected boolean isAlarm(){
return true;
}
}
HummerH1Model.java代码如下:
package com.designPattern.templateMethod;
public class HummerH1Model extends HummerModel{
private boolean alarmFlag = true;
@Override
protected void start() {
System.out.println("悍马1启动!");
}
@Override
protected void stop() {
System.out.println("悍马1停车!");
}
@Override
protected void alarm() {
System.out.println("悍马1鸣笛!");
}
@Override
protected void engineBoom() {
System.out.println("悍马1引擎启动!");
}
protected boolean isAlarm(){
return this.alarmFlag;
}
public void setAlarm(boolean isAlarm){
this.alarmFlag = isAlarm;
}
}
HummerH2Model.java代码如下:
package com.designPattern.templateMethod;
public class HummerH2Model extends HummerModel{
@Override
protected void start() {
System.out.println("悍马2发动!");
}
@Override
protected void stop() {
System.out.println("悍马2停车!");
}
@Override
protected void alarm() {
System.out.println("悍马2鸣笛!");
}
@Override
protected void engineBoom() {
System.out.println("悍马2引擎启动!");
}
public boolean isAlarm(){
return false;
}
}
Client.java代码如下:
package com.designPattern.templateMethod;
public class Client {
public static void main(String[] args) {
HummerModel h1 = new HummerH1Model();
h1.run();
HummerModel h2 = new HummerH2Model();
h2.run();
}
}
运行结果如下:
悍马1启动!
悍马1引擎启动!
悍马1鸣笛!
悍马1停车!
悍马2发动!
悍马2引擎启动!
悍马2停车!