顶层设计: 抽象类 【 汽车模型】
package com.designer.designerdemo.template; /** * 基本方法 : start(), stop(), alarm(), engineBoom() * 模板方法 : run() */ public abstract class AbstractCarModel { /** 启动 */ protected abstract void start(); /** 停止 */ protected abstract void stop(); /** 按喇叭 */ protected abstract void alarm(); /** 引擎发出声音 */ protected abstract void engineBoom(); /** 是否让喇叭响 */ protected abstract boolean isAlarm(); /** * 模板方法 * 出发 * final修饰避免子类修改它的含义 */ final public void run() { //1.启动 this.start(); //2.鸣笛 if(this.isAlarm()) this.alarm(); //3.引擎轰鸣 this.engineBoom(); //4.停车 this.stop(); } }
子类1:【奥迪汽车】
package com.designer.designerdemo.template; public class AudiCarModel extends AbstractCarModel { @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引擎轰鸣==="); } @Override protected boolean isAlarm() { return true; } }
测试
package com.designer.designerdemo; import com.designer.designerdemo.template.AbstractCarModel; import com.designer.designerdemo.template.BwmCarModel; import com.designer.designerdemo.template.AudiCarModel; public class Test { public static void main(String[] args) { BwmCarModel car = new BwmCarModel(); car.run(); } }