设计模式-命令模式

shienh 2020年01月23日 143次浏览

命令(Command)模式的定义如下:将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理。

#include <iostream>
#include <string>
#include <queue>
#include <Windows.h>
using namespace std;

//协议处理类
class   HandleClientProtocol{
public:
    void AddMoney(){
        cout<<"add money"<<endl;
    }

     void AddCoin(){
        cout<<"add coin"<<endl;
    }

     void AddLevel(){
         cout<<"add level"<<endl;
     }
};

//命令接口
class AbstractCommand{
public:
    virtual void handle()=0;//处理客户端请求接口

public:

};

class AddMoneyCommad:public AbstractCommand{
public:
    AddMoneyCommad(HandleClientProtocol* pProtocol){
        this->pProtocol = pProtocol;
    }

    virtual void handle(){
        this->pProtocol->AddMoney();
    }
public:
     HandleClientProtocol* pProtocol;
};

class AddLevelCommad:public AbstractCommand{
public:
    AddLevelCommad(HandleClientProtocol* pProtocol){
        this->pProtocol = pProtocol;
    }

    virtual void handle(){
        this->pProtocol->AddLevel();
    }
public:
     HandleClientProtocol* pProtocol;
};


class AddCoinCommad:public AbstractCommand{
public:
    AddCoinCommad(HandleClientProtocol* pProtocol){
        this->pProtocol = pProtocol;
    }

    virtual void handle(){
        this->pProtocol->AddCoin();
    }
public:
     HandleClientProtocol* pProtocol;
};

class Server{
public:
    void addRequest(AbstractCommand* cmd){
        Sleep(2000);
        command.push(cmd);
        AbstractCommand* com = command.front();
        com->handle();
        command.pop();
    }

    void startHandle(){
        while(!command.empty()){

        }
    }
public:
    queue<AbstractCommand*>command;

};

int main(int argc, char *argv[])
{
    HandleClientProtocol* protocol = new HandleClientProtocol;
    Server* server = new Server;
    AbstractCommand* addmoney = new AddMoneyCommad(protocol);
    AbstractCommand* addcoin = new AddCoinCommad(protocol);
    AbstractCommand* addlevel = new AddLevelCommad(protocol);
    server->addRequest(addmoney);
    server->addRequest(addcoin);
    server->addRequest(addlevel);
    server->startHandle();
    return 0;
}