定義
一個(gè)抽象類公開定義了執(zhí)行它的方法的方式/模板。它的子類可以按需要重寫方法實(shí)現(xiàn),但調(diào)用將以抽象類中定義的方式進(jìn)行。這種類型的設(shè)計(jì)模式屬于行為型模式。
模板模式是基于繼承的。
角色
抽象模板
具體實(shí)現(xiàn)
實(shí)例
創(chuàng)建一個(gè)抽象模板,它的模板方法用final修飾
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
public final void play(){
initialize();
startPlay();
endPlay();
}
}
創(chuàng)建具體實(shí)現(xiàn)類
public class Football extends Game {
@Override
void initialize() {
System.out.println("football game initialized, start playing");
}
@Override
void startPlay() {
System.out.println("football game started, enjoy the game");
}
@Override
void endPlay() {
System.out.println("football game finished!");
}
}
public class Basketball extends Game {
@Override
void initialize() {
System.out.println("basketball game initialized, start playing");
}
@Override
void startPlay() {
System.out.println("basketball game started, enjoy the game");
}
@Override
void endPlay() {
System.out.println("basketball game finished!");
}
}
調(diào)用模板方法
public class Test {
public static void main(String[] args) {
Game game = new Football();
game.play();
}
}
運(yùn)行結(jié)果
football game initialized, start playing
football game started, enjoy the game
football game finished!