现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

代码版设计模式17:命令者模式【行为型】

2013-03-06 12:19 工业·编程 ⁄ 共 1175字 ⁄ 字号 暂无评论

#include <iostream>
#include <list>
using namespace std;

//
class CReceiveTV
{
public:
    void OpenTV() { cout<<"open TV."<<endl; }
    void ChangeTV() { cout<<"change TV."<<endl; }
    void CloseTV() { cout<<"close TV."<<endl; }
};

struct ICommand
{
public:
    ICommand(CReceiveTV *pReceiveTV) : m_pReceiveTV(pReceiveTV) { }
    virtual ~ICommand() { }

    virtual void ExcuteCommand() = 0;

protected:
    CReceiveTV *m_pReceiveTV;
};

class COpenCommand : public ICommand
{
public:
    COpenCommand(CReceiveTV *pReceiveTV) : ICommand(pReceiveTV) { }
    virtual ~COpenCommand() { }

    virtual void ExcuteCommand() { m_pReceiveTV->OpenTV(); }
};

class CChangeCommand : public ICommand
{
public:
    CChangeCommand(CReceiveTV *pReceiveTV) : ICommand(pReceiveTV) { }
    virtual ~CChangeCommand() { }

    virtual void ExcuteCommand() { m_pReceiveTV->ChangeTV(); }
};

class CCloseCommand : public ICommand
{
public:
    CCloseCommand(CReceiveTV *pReceiveTV) : ICommand(pReceiveTV) { }
    virtual ~CCloseCommand() { }

    virtual void ExcuteCommand() { m_pReceiveTV->CloseTV(); }
};

class CInvoker
{
public:
    void Invoke(ICommand *pCommand) { pCommand->ExcuteCommand(); }
};

//
void main()
{
    CReceiveTV receiveTV;
    ICommand *pCommand = new COpenCommand(&receiveTV);

    CInvoker invoker;
    invoker.Invoke(pCommand);

    delete pCommand;
}

给我留言

留言无头像?