模板方法模式:
定义:定义一个操作算法的框架,实现步骤延迟到子类中去实现
策略模式:
定义:定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。该模式使得算法可独立于使用它的客户而变化。
注:将策略模式中的策略抽象出来,实现步骤延迟到子类中去实现,在使用策略时根据具体需求去实现对应的子类,并调用子类实现的具体策略。所以把这两种模式放在一起介绍。
代码:
class Game {
public:Game() {}virtual ~Game() {}void Run(){StartGame();}
private:virtual void StartGame() = 0;
};
class BasketBall : public Game {void StartGame() override { std::cout << "start basketball game" << std::endl;}
};
class SocketBall : public Game {void StartGame() override { std::cout << "start socketball game" << std::endl;}
};class Gamer
{
public:Gamer(Game * game){m_pGame = game;}~Gamer(){delete m_pGame;}void playGame(){if(m_pGame){m_pGame->Run();}}
private:Game* m_pGame = nullptr;
};int main() {Game *game = new BasketBall();Game *game2 = new SocketBall();Gamer gamer(game);gamer.playGame();Gamer gamer2(game2);gamer2.playGame();return 0;
}