#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相對比較好理解。設計模式