• 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;
    }
  • 相关阅读:
    web print
    datediff
    Typical AJAX
    sql中构建sql语句,再exec这条SQL语句
    ASP.NET中将数据输出到WORD、EXCEL、TXT、HTM
    sql中添加单引号
    sql语句批处理
    日期分组
    异步线程
    电脑内存大有什么好处?
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3489425.html
Copyright © 2020-2023  润新知