模板模式( Template Pattern)
优质
小牛编辑
133浏览
2023-12-01
在模板模式中,抽象类公开定义的方式/模板以执行其方法。 它的子类可以根据需要覆盖方法实现,但调用的方式与抽象类的定义相同。 此模式属于行为模式类别。
实现 (Implementation)
我们将创建一个Game抽象类,定义操作,模板方法设置为final,以便不能覆盖它。 Cricket和Football是扩展Game并覆盖其方法的具体类。
我们的演示类TemplatePatternDemo将使用Game来演示模板模式的使用。
Step 1
使用最终的模板方法创建一个抽象类。
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();
}
}
Step 2
创建扩展上述类的具体类。
Cricket.java
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!");
}
}
Step 3
使用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();
}
}
Step 4
验证输出。
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!