Command模式

在开发中,有时需要向对象发送请求,但是不知道请求的接受者是谁,被请求的操作是什么。这时可以使用command模式。

Command模式将请求封装到一个对象(Command)中,并将请求的接受者存放到具体的ConcreteCommand类中的Receiveer中。这样实现了操作的对象和操作的具体实现之间的解耦。
这里写图片描述

实现
Receiver.h

#ifndef _RECIEVER_H_
#define _RECIVEER_H_
class Reciever
{
public:
    Reciever();
    ~Reciever();
    void Action();
};
#endif

Receiver.cpp

#include "Reciever.h"
#include <iostream>

Reciever::Reciever()
{

}
Reciever::~Reciever()
{

}
void Reciever::Action()
{
    std::cout << "Reciever Action()" << std::endl;
}

Command.h

#ifndef _COMMAND_H_
#define _COMMAND_H_
class Reciever;
class Command
{
public:
    virtual ~Command();
    virtual void Excute() = 0;
protected:
    Command();
};

class ConcreteCommand :public Command
{
public:
    ConcreteCommand(Reciever* rev);
    ~ConcreteCommand();
    void Excute();
private:
    Reciever* rev_;
};
#endif

Command.cpp

#include "Command.h"
#include "Reciever.h"
#include <iostream>

Command::Command()
{}
Command::~Command()
{}

ConcreteCommand::ConcreteCommand(Reciever* rev)
{
    rev_ = rev;
}
ConcreteCommand::~ConcreteCommand()
{
    delete rev_;
    rev_ = NULL;
}
void ConcreteCommand::Excute()
{
    rev_->Action();
}

Invoker.h

#ifndef _INVOKER_H_
#define _INVOKER_H_
class Command;
class Invoker
{
public:
    Invoker(Command* cmd);
    ~Invoker();
    void Invoke();
private:
    Command* cmd_;
};
#endif

Invoker.cpp

#include "Command.h"
#include "Invoker.h"
#include <iostream>

Invoker::Invoker(Command* cmd)
{
    cmd_ = cmd;
}
Invoker::~Invoker()
{
    delete cmd_;
    cmd_ = NULL;
}
void Invoker::Invoke()
{
    cmd_->Excute();
}

main.cpp

#include "Command.h"
#include "Invoker.h"
#include "Reciever.h"

int main()
{
    Reciever* rev = new Reciever();
    Command* cmd = new ConcreteCommand(rev);
    Invoker* inv = new Invoker(cmd);
    inv->Invoke();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值