标签:sys 输出 开始游戏 oid href 结束 rac htm bst
通过抽象函数定义一个模板,模板中定义抽象的函数。所有继承实现该类的子类都按照自己的实际需求实现其中的类,这样,就把这个抽象类当做了模板。
//模板类 public abstract class Game { abstract void initialize(); abstract void startPlay(); abstract void endPlay(); //模板 public final void play(){ //初始化游戏 initialize(); //开始游戏 startPlay(); //结束游戏 endPlay(); } } //根据模板类实现实体类 //实体类1 public 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!"); } } //实体类2 public 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!
代码来源: 特别感谢 菜鸟教程 java设计模式之模板模式
标签:sys 输出 开始游戏 oid href 结束 rac htm bst
原文地址:http://www.cnblogs.com/K-artorias/p/7976050.html