Design Pattern 简明教程
Design Patterns - Template Pattern
在模板模式中,抽象类暴露出定义的方法/模板来执行其方法。它的子类可以根据需要覆盖方法实现,但调用必须按照抽象类定义的方式进行。此模式属于行为模式类别。
In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined by an abstract class. This pattern comes under behavior pattern category.
Implementation
我们将创建一个定义操作的抽象类 Game,并将其模板方法设置为 final,这样就无法覆盖它。Cricket 和 Football 是扩展 Game 并覆盖其方法的具体类。
We are going to create a Game abstract class defining operations with a template method set to be final so that it cannot be overridden. Cricket and Football are concrete classes that extend Game and override its methods.
我们的演示类 TemplatePatternDemo 将使用 Game 来演示模板模式的使用。
TemplatePatternDemo, our demo class, will use Game to demonstrate use of template pattern.

Step 1
创建带有 final 模板方法的抽象类。
Create an abstract class with a template method being final.
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
创建一个扩展上述类的具体类。
Create concrete classes extending the above class.
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() 来展示一种定义好的比赛玩法。
Use the Game’s template method play() to demonstrate a defined way of playing game.
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();
}
}