📅  最后修改于: 2020-12-21 02:06:10             🧑  作者: Mango
在模板模式中,抽象类公开定义的方式/模板来执行其方法。它的子类可以根据需要重写方法的实现,但是调用的方式应与抽象类定义的方式相同。此模式属于行为模式类别。
我们将创建一个Game抽象类,该类定义将模板方法设置为final的操作,以使其无法被覆盖。板球和足球是扩展Game并覆盖其方法的具体类。
我们的演示类TemplatePatternDemo将使用Game演示模板模式的使用。
使用最终的模板方法创建一个抽象类。
Game.java
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
//template method
public final void play(){
//initialize the game
initialize();
//start game
startPlay();
//end game
endPlay();
}
}
创建扩展上述类的具体类。
板球
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!");
}
}
Football.java
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!");
}
}
使用Game的模板方法play()演示定义的玩游戏方式。
TemplatePatternDemo.java
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!