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
- Command模式
- Command模式
- Command模式
- Command 模式
- Command 模式
- Command模式
- command模式
- Command模式
- Command模式
- Command模式
- Command 模式
- Command 模式
- Command模式
- Command模式
- Command模式
- COMMAND 模式
- Command模式
- Command模式
- 欢迎使用CSDN-markdown编辑器
- C# ISupportInitialize的使用
- 欢迎使用CSDN-markdown编辑器
- C#中out和ref之间的区别
- hdu 5370 Tree Maker(catalan+dp)
- Command模式
- yield() sleep()wait()区别
- 第84讲:Scala中List和ListBuffer设计实现思考学习笔记
- Leetcode63 Unique Paths II
- internal 修饰符起什么作用?
- 不确定的问题 2015-8-12
- android控件--ViewPager原理及实现
- ViewDragHelper详解
- easy_install安装,更新模块 python