//方式一
//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; }
原文地址:https://www.cnblogs.com/fourmi/p/12085089.html
时间: 2024-10-07 05:09:11