Command模式

来源:互联网 发布:android http网络协议 编辑:程序博客网 时间:2024/06/18 03:53

在开发中,有时需要向对象发送请求,但是不知道请求的接受者是谁,被请求的操作是什么。这时可以使用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
原创粉丝点击