設計模式之對象行爲型模式 — COMMAND (命令)模式

意圖

將一個請求封裝成一個對象 ,從而使你可以用不同的請求對客戶進行參數化。對請求進行排隊或者記錄請求日誌,以及支持可撤銷的操作。

對象交互圖

這裏寫圖片描述

  • Command 執行操作的接口
  • client 創建具體的命令對象以及接受者
  • Invoker 要求該命令執行的這個請求
  • Receiver 接受者,任何類都可以作爲接受者

代碼示例

//test.h文件

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

//接受者
class Receiver
{
public:
    Receiver();
    ~Receiver();

    void Action();
protected:
private:
};


//命令的抽象基類
class Command
{
public:
    virtual ~Command();
    virtual void Execute() = 0;
protected:
    Command();
private:
};

//Ex指令  
class ExCommand:public Command
{
public:
    ExCommand(Receiver *re);
    ~ExCommand();

    virtual void Execute();
protected:
private:
    Receiver *m_re;
};
//Ac指令
class AcCommand :public Command
{
public:
    AcCommand();
    ~AcCommand();
    virtual void Execute();

private:

};


//指令序列Bc  由Ex和Ac組合而成 
class BcCommmand:public Command
{
public:
    BcCommmand();
    virtual ~BcCommmand();

    virtual void Add(Command *);
    virtual void Remove(Command *);

    virtual void Execute();

private:
    list <Command *> *m_com;
};

//test.cpp 文件

#include "test.h"

Command::~Command()
{

}


Command::Command()
{

}

/****************************/

Receiver::Receiver()
{

}

Receiver::~Receiver()
{

}

void Receiver::Action()
{
    cout << "正在執行操作" << endl;
}
/*************************************/
ExCommand::ExCommand(Receiver *re)
:Command(), m_re(re)
{

}

ExCommand::~ExCommand()
{

}

void ExCommand::Execute()
{
    cout <<"正在執行Ex指令 \n"<< "調用接受者\n....." << endl;
    m_re->Action();
}


AcCommand::AcCommand()
{

}

AcCommand::~AcCommand()
{
}

void AcCommand::Execute()
{
    cout << "正在執行Ac指令" << endl;
}

/*********************************/

BcCommmand::BcCommmand()
{
    m_com = new list<Command *>();
}

BcCommmand::~BcCommmand()
{
}

void BcCommmand::Add(Command *com)
{
    m_com->push_back(com);
}

void BcCommmand::Remove(Command *com)
{
    m_com->remove(com);
}

void BcCommmand::Execute()
{
    for (auto x:*m_com)
    {
        x->Execute();
    }
}

//main.cpp 文件  

#include "test.h"

int main()
{
    int a = 0;
    cout << "輸入 1 執行Ex操作  \n輸入 2 執行Ac 操作  \n輸入 3 執行Bc 操作" << endl;
    Receiver *re = new Receiver();

    ExCommand *ex = new ExCommand(re);
    AcCommand *ac = new AcCommand();

    BcCommmand *bc = new BcCommmand();
    bc->Add(ex);
    bc->Add(ac);

    while (cin>>a)
    {
        switch (a)
        {
        case 1:   //Invoker  
            ex->Execute();
            break;
        case 2:
            ac->Execute();
            break;
        case 3:
            bc->Execute();
            break;
        default:
            break;
        }

    }
    system("pause");
    return 0;
}

效果

  1. 將調用操作的對象與知道如何實現操作的對象解耦
  2. 可以將多個命令裝配成一個複合命令
  3. 新增加命令也很容易,無需改變已有的類

我的個人網站 http://www.breeziness.cn/
我的CSDN http://blog.csdn.net/qq_33775402

轉載請註明出處 小風code www.breeziness.cn

發佈了78 篇原創文章 · 獲贊 75 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章