C++设计模式之命令模式

我们去餐厅吃饭,我们是通过服务员来点菜,具体是谁来做这些菜和他们什么时候完成的这些菜,其实我们都不知道。抽象之,“菜单请求者”我们和“菜单实现者”厨师,2者之间是松耦合的,我们对这些菜的其他一些请求比如“撤销,重做”等,我们也不知道是谁在做。其实这就是本文要说的Command模式。

        将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。[GOF 《设计模式》]

UML类图:

代码实现:

// Command.cpp : 定义控制台应用程序的入口点。
//

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

// 烤肉师傅

class RoastCook
{
public:
    void MakeMutton() { cout << "烤羊肉" << endl; }
    void MakeChickenWing() { cout << "烤鸡翅膀" << endl; }
};

// 抽象命令类
class Command
{
public:
    Command(RoastCook* temp) { receiver = temp; }
    virtual void ExecuteCmd() = 0;
protected:
    RoastCook* receiver;

};

// 烤羊肉命令

class MakeMuttonCmd : public Command
{
public:
    MakeMuttonCmd(RoastCook* temp) : Command(temp) {}
    virtual void ExecuteCmd() { receiver->MakeMutton(); }
};

class MakeChickenWingCmd : public Command
{
public:
    MakeChickenWingCmd(RoastCook* temp) : Command(temp) {}
    virtual void ExecuteCmd() { receiver->MakeChickenWing(); }
};

// 服务员类

class Waiter
{
public:
    void SetCmd(Command* temp);
    // 通知执行
    void Notify();
protected:
    vector<Command*> m_commandList;

};

void Waiter::SetCmd(Command* temp)
{
    m_commandList.push_back(temp);
    cout << "增加订单" << endl;
}



void Waiter::Notify()
{
    vector<Command*>::iterator it;
    for (it=m_commandList.begin(); it!=m_commandList.end(); ++it)
    {
        (*it)->ExecuteCmd();
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    RoastCook* cook = new RoastCook();
    Command* cmd1 = new MakeMuttonCmd(cook);
    Command* cmd2 = new MakeChickenWingCmd(cook);
    Waiter* girl = new Waiter();

    // 点菜
    girl->SetCmd(cmd1);
    girl->SetCmd(cmd2);

    // 服务员通知
    girl->Notify();
    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wxmwanggood/p/9300801.html