标签:行为模式 protect getch tchar cte cut 请求 ret action
//方式一
//Reciever.h
#pragma once class Reciever{ public: Reciever(); ~Reciever(); void Action(); protected: private: };
//Reciever.cpp
#include"Reciever.h" #include<iostream> Reciever::Reciever(){} Reciever::~Reciever(){} void Reciever::Action() { std::cout << "Reciever action ..." << std::endl; }
//Command.h
#pragma once class Reciever; class Command{ public: virtual ~Command(); virtual void Execute() = 0; protected: Command(); private: }; class ConcreateCommand :public Command { public: ConcreateCommand(Reciever* rec); ~ConcreateCommand(); void Execute(); protected: private: Reciever* _rec; };
//Command.cpp
#include"Command.h" #include"Reciever.h" #include<iostream> Command::Command(){} Command::~Command(){} void Command::Execute(){} ConcreateCommand::ConcreateCommand(Reciever* rec) { _rec = rec; } ConcreateCommand::~ConcreateCommand() { delete this->_rec; } void ConcreateCommand::Execute() { _rec->Action(); std::cout << "ConcreateCommand ..." << std::endl; }
//Invoker.h
class Command; class Invoker { public: Invoker(Command* cmd); ~Invoker(); void Invoke(); protected: private: Command* _cmd; };
//Invoker.cpp
#include"Command.h" #include"Invoker.h" #include<iostream> Invoker::Invoker(Command* cmd) { _cmd = cmd; } Invoker::~Invoker() { delete _cmd; } void Invoker::Invoke() { _cmd->Execute(); }
//main.cpp
#include"Command.h" #include"Invoker.h" #include"Reciever.h" #include<iostream> #include<string> int main(int args, char* argv) { Reciever* rec = new Reciever(); Command* cmd = new ConcreateCommand(rec); Invoker* inv = new Invoker(cmd); inv->Invoke(); getchar(); return 0; }
设计模式-Command(行为模式) 将一个请求封装到一个Command类中,提供一个处理对象Receiver,将Command由Invoker激活。
标签:行为模式 protect getch tchar cte cut 请求 ret action
原文地址:https://www.cnblogs.com/fourmi/p/12085089.html