描述
通过抽象函数定义一个模板,模板中定义抽象的函数。所有继承实现该类的子类都按照自己的实际需求实现其中的类,这样,就把这个抽象类当做了模板。
实例
//模板类public abstract class Game { abstract void initialize(); abstract void startPlay(); abstract void endPlay(); //模板 public final void play(){ //初始化游戏 initialize(); //开始游戏 startPlay(); //结束游戏 endPlay(); }}//根据模板类实现实体类//实体类1public class Cricket extends Game { @Override void endPlay() { System.out.println("Cricket Game Finished!"); } @Override void initialize() { System.out.println("Cricket Game Initialized! Start playing."); } @Override void startPlay() { System.out.println("Cricket Game Started. Enjoy the game!"); }}//实体类2public class Football extends Game { @Override void endPlay() { System.out.println("Football Game Finished!"); } @Override void initialize() { System.out.println("Football Game Initialized! Start playing."); } @Override void startPlay() { System.out.println("Football Game Started. Enjoy the game!"); }}//主函数public class TemplatePatternDemo { public static void main(String[] args) { Game game = new Cricket(); game.play(); System.out.println(); game = new Football(); game.play(); }}输出结果:Cricket Game Initialized! Start playing.Cricket Game Started. Enjoy the game!Cricket Game Finished!Football Game Initialized! Start playing.Football Game Started. Enjoy the game!Football Game Finished!
代码来源: 特别感谢