模板模式
Posted K_artorias
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模板模式相关的知识,希望对你有一定的参考价值。
描述
通过抽象函数定义一个模板,模板中定义抽象的函数。所有继承实现该类的子类都按照自己的实际需求实现其中的类,这样,就把这个抽象类当做了模板。
实例
//模板类 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设计模式之模板模式
以上是关于模板模式的主要内容,如果未能解决你的问题,请参考以下文章