1

简介

命令模式,将一个请求封装成一个对象,因此你可以将不同的请求封装成不同的对象,实现调用操作的对象和实际处理的对象之间的解耦;对请求排队或者记录日志,以及支持可撤销操作。

UML类图

clipboard.png

示例

电视机遥控器可以看作UML图中的CInvoker类,动作的请求者,开和关等按钮可以看作是CCommand类,真正执行开和关的电视机可以看作是动作的接收者CReceiver。
command,invoker和receiver类

#ifndef COMMAND_H
#define COMMAND_H
#include <vector>
using namespace std;

class CReceiver
{
public:
    virtual void ExecuteOpenAction() = 0;
    virtual void ExecuteCloseAction() = 0;
};
class CTelevisionReceiver:public CReceiver
{
public:
    void ExecuteOpenAction(){}
    void ExecuteCloseAction(){}
};

class CCommand
{
public:
    CCommand(CReceiver* pReceiver):m_pReceiver(pReceiver){}
    virtual void Execute() = 0;
protected:
    CReceiver* m_pReceiver;
};

class COpenCommand:public CCommand
{
public:
    COpenCommand(CReceiver* pReceiver):CCommand(pReceiver){}
    void Execute()
    {
        m_pReceiver->ExecuteOpenAction();
    }
};

class CCloseCommand:public CCommand
{
public:
    CCloseCommand(CReceiver* pReceiver):CCommand(pReceiver){}
    void Execute()
    {
        m_pReceiver->ExecuteCloseAction();
    }
};

class CRemoteControl
{
public:
    void Execute(CCommand* pCommand)
    {
        m_commandList.push_back(pCommand);//可选,保存历史命令
        pCommand->Execute();
    }
private:
    vector<CCommand*> m_commandList;
};

#endif

客户端调用,main.cpp

#include "command.h"
#define SAFE_DELETE(p) if(p){delete (p); (p) = NULL;}

int main(int argc, char* argv[])
{
    CReceiver* pReceiver = new CTelevisionReceiver;
    CCommand* pOpenCommand = new COpenCommand(pReceiver);
    CCommand* pCloseCommand = new CCloseCommand(pReceiver);

    CRemoteControl* pRemoteControl = new CRemoteControl;
    pRemoteControl->Execute(pOpenCommand);
    pRemoteControl->Execute(pCloseCommand);
    SAFE_DELETE(pRemoteControl);
    SAFE_DELETE(pCloseCommand);
    SAFE_DELETE(pOpenCommand);
    SAFE_DELETE(pReceiver);
    return 0;
}

one_piece
26 声望8 粉丝

« 上一篇
责任链模式
下一篇 »
解释器模式