设计模式-命令模式

使用情境:把操作的请求者与请求的执行者分离开.添加新命令类型,不影响已有的命令.

这里写图片描述

// receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H

class Receiver
{
public:
    Receiver();
    virtual void ExecuteCommandA();
    virtual void ExecuteCommandB();
};

#endif // RECEIVER_H
// receiver.cpp
#include "receiver.h"
#include <iostream>

Receiver::Receiver(){}

void Receiver::ExecuteCommandA()
{
    std::cout << "receiver execute command AAA" << std::endl;
}

void Receiver::ExecuteCommandB()
{
    std::cout << "receiver execute command BBB" << std::endl;
}
// command.h
#ifndef COMMAND_H
#define COMMAND_H

#include "receiver.h"

class Command
{
public:
    Command(Receiver* temp);
    virtual void ExecuteCmd() = 0;
protected:
    Receiver* m_receiver;
};

#endif // COMMAND_H
// command.cpp
#include "command.h"

Command::Command(Receiver *temp)
{
    m_receiver = temp;
}
// concretecommanda.h
#ifndef CONCRETECOMMANDA_H
#define CONCRETECOMMANDA_H

#include "command.h"

class ConcreteCommandA : public Command
{
public:
    ConcreteCommandA(Receiver* temp);
    virtual void ExecuteCmd();
};

#endif // CONCRETECOMMANDA_H
// concretecommand.cpp
#include "concretecommanda.h"

ConcreteCommandA::ConcreteCommandA(Receiver *temp) : Command(temp)
{}

void ConcreteCommandA::ExecuteCmd()
{
    m_receiver->ExecuteCommandA();
}
// invoker.h
#ifndef INVOKER_H
#define INVOKER_H

#include "command.h"
#include <vector>

class Invoker
{
public:
    Invoker();
    void SetCmd(Command* tmp);
    void Notify();
protected:
    std::vector<Command*> m_commandList;
};

#endif // INVOKER_H
// invoker.cpp
#include "invoker.h"
#include <iostream>

Invoker::Invoker(){}

void Invoker::SetCmd(Command *tmp)
{
    m_commandList.push_back(tmp);
    std::cout << "add command" << std::endl;
}

void Invoker::Notify()
{
    for( std::vector<Command*>::iterator it = m_commandList.begin();
         it != m_commandList.end(); it++)
    {
        (*it)->ExecuteCmd();
    }
}

客户端:

// main.cpp
#include <iostream>
#include "command.h"
#include "receiver.h"
#include "concretecommanda.h"
#include "invoker.h"

using namespace std;

int main(int argc, char *argv[])
{
    Receiver* receiver = new Receiver();
    Command* command = new ConcreteCommandA(receiver);
    Invoker* invoker = new Invoker();

    invoker->SetCmd(command);
    invoker->Notify();

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值