命令模式

来源:互联网 发布:上海华讯网络系统有 编辑:程序博客网 时间:2024/06/07 00:54
// ConsoleApplication19.cpp : Defines the entry point for the console application.//#include "stdafx.h"/*是一个抽象类,类中对需要执行的命令进行声明,一般来说要对外公布一个execute方法用来执行命令*/class Command{public:virtual void execute()=0;  //C++声明纯虚函数才可以重载?};//调用者 负责调用命令class Invoker{private:Command *command;public:void SetCommand(Command *c){this->command = c;}void Action(){this->command->execute();}};//接收者 负责接收命令并且执行class Receiver{public:void DoSomething(){cout<<"接受-业务逻辑处理"<<endl;}};//具体的command实现类class ConcreteCommand:public Command{private:Receiver *receiver;public:ConcreteCommand(Receiver *r){this->receiver = r;}void execute(){this->receiver->DoSomething();}};int _tmain(int argc, _TCHAR* argv[]){Receiver *r = new Receiver();Command *command = new ConcreteCommand(r);Invoker *invoker = new Invoker();invoker->SetCommand(command);invoker->Action();return 0;}

0 0
原创粉丝点击