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!"); } }publicclassOperationAddimplementsStrategy{ @Override publicintdoOperation(int num1, int num2){ return num1 + num2; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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!"); } }
步骤 3
使用 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(); } }
步骤 4
执行程序,输出结果:
1 2 3 4 5 6 7
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!
Copyright 2021 sunfy.top ALL Rights Reserved