#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相对比较好理解。设计模式