設計模式之-模版模式(Template Pattern)

模板模式

在模板模式(Template Pattern)中,一個抽象類公開定義了執行它的方法的方式/模板。它的子類能夠按須要重寫方法實現,但調用將以抽象類中定義的方式進行。這種類型的設計模式屬於行爲型模式。
C++代碼:
#include<iostream>
using namespace std;

class Game {
public:
   virtual void initialize() = 0;
   virtual void startPlay() = 0;
   virtual void endPlay() = 0;
 
public:
    void play(){
      //初始化遊戲
      initialize();
      //開始遊戲
      startPlay();
      //結束遊戲
      endPlay();
   }
};

class Cricket :public Game {
public:
    void endPlay() {
        cout<<"Cricket Game Finished!"<<endl;
    }
    void initialize() {
        cout<<"Cricket Game Initialized! Start playing."<<endl;
    }
    void startPlay() {
        cout<<"Cricket Game Started. Enjoy the game!"<<endl;
    }
};



class Football:public Game {
public:
    void endPlay() {
        cout<<"Football Game Finished!"<<endl;
    }

    void initialize() {
        cout<<"Football Game Initialized! Start playing."<<endl;
    }
    void startPlay() {
        cout<<"Football Game Started. Enjoy the game!"<<endl;
    }
};



int main(){
    Game* game = new Cricket();
    game->play();
    cout<<endl;
    game = new Football();
    game->play();   
}

類圖:ios

 

抽象類把主調流程完成了,子類經過具體化相關具體過程實現不一樣的效果,Template Method相對比較好理解。設計模式

相關文章
相關標籤/搜索