命令模式

60次阅读

共计 1547 个字符,预计需要花费 4 分钟才能阅读完成。

简介

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

UML 类图

示例

电视机遥控器可以看作 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;
}

正文完
 0