定义
父类(抽象类)定义了方法的执行步骤,但是不定义具体的执行逻辑,由子类决定父类的行为。
UML类图
代码
抽象类定义玩的动作,分初始化游戏、开始游戏、结束游戏。但是没有定义其中的具体执行细节。
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
public final void play(){
initialize();
startPlay();
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!");
}
}
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!");
}
}
DEMO
public class TemplatePatternDemo {
public static void main(String[] args) {
Game game = new Cricket();
game.play();
System.out.println();
game = new Football();
game.play();
}
}
总结
模版方法其实是定义了钩子方法,由子类决定钩子方法的实现逻辑。总之,由子类决定父类的行文。
|