《大話設計模式》讀書筆記之C++實現--chapter23命令模式

#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
#include <QCoreApplication>
using namespace std;

//抽象接受命令類,執行命令
class AbstractReceiver{
public:
    virtual void ExcuteCommand() = 0;
    virtual ~AbstractReceiver(){}
};

//抽象命令類,有純虛函數ExcuteCommand來執行命令
class AbstractCommand{
public:
    virtual void ExcuteCommand() = 0;
    virtual ~AbstractCommand(){}
};

//具體命令類,在構造函數中指定執行命令的receiver來執行命令
class ConcreteCommandOne:public AbstractCommand{
public:
    explicit ConcreteCommandOne(AbstractReceiver *receiver):m_pReceiver(receiver){}
    void ExcuteCommand()
    {
        m_pReceiver->ExcuteCommand();
        cout << "command is One" << endl;
    }
protected:
    AbstractReceiver* m_pReceiver;
};

class ConcreteCommandTwo:public AbstractCommand{
public:
    explicit ConcreteCommandTwo(AbstractReceiver *receiver):m_pReceiver(receiver){}
    void ExcuteCommand()
    {
        m_pReceiver->ExcuteCommand();
        cout << "command is two" << endl;
    }
protected:
    AbstractReceiver* m_pReceiver;
};

//具體命令接受者類,可執行不同的命令
class ConcreteReceiverOne:public AbstractReceiver{
public:
    void ExcuteCommand()
    {
        cout << "ConcreteReceiverOne excute command" << endl;
    }
};

//命令請求類,負責命令的設置,刪除,記錄及通知。
class Invoker{
public:
    void SetCommand(AbstractCommand* command)
    {
        m_CommandList.push_back(command);
    }
    void RemoveCommand(AbstractCommand* command)
    {
        m_CommandList.remove(command);
    }

    void Notify()
    {
        foreach (auto command, m_CommandList)
        {
            command->ExcuteCommand();
        }
    }
private:
    list<AbstractCommand *> m_CommandList;
};

int main(int argc,char** argv)
{
    AbstractReceiver* receiver = new ConcreteReceiverOne();         //指定一個命令執行者
    AbstractCommand* command1 = new ConcreteCommandOne(receiver);   //命令1指定命令執行者爲receiver
    AbstractCommand* command2 = new ConcreteCommandTwo(receiver);   //命令2指定命令執行者爲receiver
    Invoker invoker;
    invoker.SetCommand(command1);                                   //命令請求者設置命令請求
    invoker.SetCommand(command2);
    invoker.Notify();                                               //命令請求者通知所有命令,請求執行
    cout << "cancle command one" << endl;
    invoker.RemoveCommand(command1);                                //命令請求者設取消命令請求
    invoker.Notify();

    //刪除指針
    if(command1 != nullptr)
    {
        delete command1;
        command1 = nullptr;
    }
    if(command2 != nullptr)
    {
        delete command2;
        command2 = nullptr;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章