1. 程式人生 > 其它 >java設計模式 --模板方法

java設計模式 --模板方法

1.什麼是模板方法?

       模板方法模型是一種行為設計模型。模板方法是一個定義在父類的方法,在模板方法中會呼叫多個定義在父類別的其他方法,而這些方法有可能只是抽象方法並沒有實現,模板方法僅決定這些抽象方法的執行順序,這些抽象方法的實作由子類別負責,並且子類不允許覆寫模板方法。

 

2.舉例

/**
  * An abstract class that is common to several games in
  * which players play against the others, but only one is
  * playing at a given time.
  
*/ abstract class Game { private int playersCount; abstract void initializeGame(); abstract void makePlay(int player); abstract boolean endOfGame(); abstract void printWinner(); /* A template method : */ final void playOneGame(int playersCount) {
this.playersCount = playersCount; initializeGame(); int j = 0; while (!endOfGame()){ makePlay(j); j = (j + 1) % playersCount; } printWinner(); } } //Now we can extend this class in order to implement actual games: class Monopoly extends
Game { /* Implementation of necessary concrete methods */ void initializeGame() { // ... } void makePlay(int player) { // ... } boolean endOfGame() { // ... } void printWinner() { // ... } /* Specific declarations for the Monopoly game. */ // ... } class Chess extends Game { /* Implementation of necessary concrete methods */ void initializeGame() { // ... } void makePlay(int player) { // ... } boolean endOfGame() { // ... } void printWinner() { // ... } /* Specific declarations for the chess game. */ // ... } public class Player { public static void main(String[] args) { Game chessGame = new Chess(); chessGame.initializeGame(); chessGame.playOneGame(1); //call template method } }

 

3.模板方法的優點

  • 封裝不變部分, 擴充套件可變部分
  • 把認為是不變部分的演算法封裝到父類實現, 而可變部分的則可以通過繼承來繼續擴充套件。
  • 提取公共部分程式碼, 便於維護
  • 行為由父類控制, 子類實現
  • 基本方法是由子類實現的, 因此子類可以通過擴充套件的方式增加相應的功能, 符合開閉原則。

常見如spring中AbstractApplicationContext的refresh()方法。