首页 > 代码库 > Command
Command
#include <iostream>using namespace std;#define DESTROY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; }class Receiver{public: void Action1() { cout<<"Receiver::Action1"<<endl; } void Action2() { cout<<"Receiver::Action2"<<endl; } void Action3() { cout<<"Receiver::Action3"<<endl; }};class Command{public: Command(Receiver* pReceiver) { m_pReceiver = pReceiver; } virtual ~Command() { DESTROY_POINTER(m_pReceiver); } virtual void Execute()=0;protected: Receiver* m_pReceiver;};class ConcreteCommandA : public Command{public: ConcreteCommandA(Receiver* pReceiver) : Command(pReceiver) {} virtual void Execute() { m_pReceiver->Action1(); }};class ConcreteCommandB : public Command{public: ConcreteCommandB(Receiver* pReceiver) : Command(pReceiver) {} virtual void Execute() { m_pReceiver->Action2(); }};class ConcreteCommandC : public Command{public: ConcreteCommandC(Receiver* pReceiver) : Command(pReceiver) {} virtual void Execute() { m_pReceiver->Action3(); }};class Invoker{public: Invoker(Command* pCommand) { m_pCommand = pCommand; } ~Invoker() { DESTROY_POINTER(m_pCommand); } void Request() { m_pCommand->Execute(); }private: Command* m_pCommand;};int main(int argc, char *argv[]){ Receiver* pReceiver = new Receiver; Invoker invoker1(new ConcreteCommandA(pReceiver)); invoker1.Request(); Invoker invoker2(new ConcreteCommandB(pReceiver)); invoker2.Request(); Invoker invoker3(new ConcreteCommandC(pReceiver)); invoker3.Request(); return 0;}
Command
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。