c++ 命令模式(command)

命令模式的有点:

1.能够容易地设计一个命令队列;

2.在需要的情况下,可以比较容易地将命令记入日志。

3.可以容易的实现对请求的撤销和重做。

4.由于加进新的具体命令类不影响其他的类,因此增加新的具体命令类很容易。

#include <iostream>
#include <vector>

using namespace std;

class Reciever
{
public:
    void Action()
    {
        cout << "Do action !!" <<endl;
    }
};

class Icommand
{
public:
    virtual ~Icommand() {}
    virtual void Excute() = 0;
protected:
    Icommand() {}
};

class Read_Command:public Icommand
{
public:
    Read_Command(Reciever *rev):m_rev(rev)
    {
        
    }
    virtual void Excute() 
    {
        cout << "Read Command.." << endl;
        m_rev->Action();
    }
    ~Read_Command()
    {
    
    }
private:
    Reciever *m_rev;
};

class Write_Command:public Icommand
{
public:
    Write_Command(Reciever *rev):m_rev(rev)
    {
        
    }
    virtual void Excute() 
    {
        cout << "Read Command.." << endl;
        m_rev->Action();
    }
    ~Write_Command()
    {
    
    }
private:
    Reciever *m_rev;
};

class Invoker
{
public:
    Invoker(Icommand* cmd):m_cmd(cmd)
    {
        
    }
    Invoker()
    {
    
    }
    ~Invoker()
    {
        delete m_cmd;
    }
    void Notify()
    {
        std::vector<Icommand*>::iterator it = cmdList.begin();
        for(it;it != cmdList.end();++it)
        {
            m_cmd = *it;
            m_cmd->Excute();
        }
    }
    void AddCmd(Icommand* pcmd)
    {
        cmdList.push_back(pcmd);
    }
    void DelCmd(Icommand* pcmd)
    {
        //cmdList.pop_back();
    }

private:
    Icommand* m_cmd;
    std::vector<Icommand*> cmdList;
};

主函数:

#include <iostream>
#include <vector>
#include "command.h"

using namespace std;

int main()
{
    Reciever* rev = new Reciever();
    Icommand* cmd1 = new Read_Command(rev);
    Icommand* cmd2 = new Write_Command(rev);
    Invoker inv;

    inv.AddCmd(cmd1);
    inv.AddCmd(cmd2);
    inv.Notify();
    
    system("pause");
    return 0;
}

 

posted @ 2013-12-24 17:24  onlycxue  阅读(4025)  评论(0编辑  收藏  举报