首页 > 代码库 > 命令模式之C++实现

命令模式之C++实现

 

 

#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;

class Kitchener
{
public:
    void MakeHamburger()
    {
        cout << "做汉堡包" << endl;
    }

    void MakeChips()
    {
        cout << "做薯条" << endl;
    }

    void MakeCake()
    {
        cout << "做蛋糕" << endl;
    }
};

class Command
{
protected:
    Kitchener *pKitchener;
public:
    Command(Kitchener *kitchener)
    {
        pKitchener = kitchener;
    }

    virtual void MakeFood() = 0;
};

class CakeCommad : public Command
{
public:
    CakeCommad(Kitchener *kitchener) : Command(kitchener){}
    virtual void MakeFood()
    {
        pKitchener->MakeCake();
    }
};

class ChipsCommad : public Command
{
public:
    ChipsCommad(Kitchener *kitchener) : Command(kitchener){}
    virtual void MakeFood()
    {
        pKitchener->MakeChips();
    }
};

class HamburgerCommad : public Command
{
public:
    HamburgerCommad(Kitchener *kitchener) : Command(kitchener){}
    virtual void MakeFood()
    {
        pKitchener->MakeHamburger();
    }
};


class Waiter
{
private:
    vector<Command*> m_vecCmd;
public:

    void AddCommand(Command *command)
    {
        m_vecCmd.push_back(command);
    }

    void MoveCommand(Command *command)
    {
        for (vector<Command*>::iterator it = m_vecCmd.begin(); it != m_vecCmd.end(); )
        {
            if (*it = command)
            {
                m_vecCmd.erase(it);
                break;
            }
            it++;
        }
    }

    void Notify()
    {
        Command* pCommad = NULL;
        for (vector<Command*>::iterator it = m_vecCmd.begin(); it != m_vecCmd.end(); it++)
        {
            pCommad = *it;
            pCommad->MakeFood();
        }
    }
};

int main()
{
    Kitchener *pKitchener = new Kitchener;
    Command *pCommand1 = new CakeCommad(pKitchener);
    Command *pCommand2 = new ChipsCommad(pKitchener);
    Command *pCommand3 = new HamburgerCommad(pKitchener);
    Waiter *pWaiter = new Waiter;
    pWaiter->AddCommand(pCommand1);
    pWaiter->AddCommand(pCommand2);
    pWaiter->AddCommand(pCommand3);
    pWaiter->MoveCommand(pCommand1);
    pWaiter->Notify();
    return 0;
}