设计模式之模板模式
1.抽象类
package com.example.demo.templete; public abstract class HummerModel { public abstract void start(); public abstract void stop(); public abstract void alarm(); public abstract void engineBoom(); /** * 共性的方法,也是模板方法模式的体现 */ public final void run()
{
this.start();
this.engineBoom();
this.alarm();
this.stop();
}
}
2.实现子类1
package com.example.demo.templete; public class HummerH1Model extends HummerModel { @Override public void start() { System.out.println("悍马H1发动..."); } @Override public void stop() { System.out.println("悍马H1停车..."); } @Override public void alarm() { System.out.println("悍马H1鸣笛..."); } @Override public void engineBoom() { System.out.println("悍马H1引擎声音是这样的..."); } }
3、实现子类2
package com.example.demo.templete; public class HummerH2Model extends HummerModel { @Override public void start() { System.out.println("悍马H2发动..."); } @Override public void stop() { System.out.println("悍马H2停车..."); } @Override public void alarm() { System.out.println("悍马H2鸣笛..."); } @Override public void engineBoom() { System.out.println("悍马H2引擎声音是这样的..."); } }
4.场景类
package com.example.demo.templete; public class Client { public static void main(String[] args) { HummerModel h1 = new HummerH1Model(); h1.run(); } }