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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM