publicclassCricketextendsGame{ @Override voidendPlay(){ System.out.println("Cricket Game Finished!"); } @Override voidinitialize(){ System.out.println("Cricket Game Initialized! Start playing."); } @Override voidstartPlay(){ System.out.println("Cricket Game Started. Enjoy the game!"); } }
publicclassFootballextendsGame{ @Override voidendPlay(){ System.out.println("Football Game Finished!"); } @Override voidinitialize(){ System.out.println("Football Game Initialized! Start playing."); } @Override voidstartPlay(){ System.out.println("Football Game Started. Enjoy the game!"); } }
demo
使用 Game 的模板方法 play() 来演示游戏的定义方式。
1 2 3 4 5 6 7 8 9 10
publicclassTemplatePatternDemo{ publicstaticvoidmain(String[] args){ Game game = new Cricket(); game.play(); System.out.println(); game = new Football(); game.play(); } }