首页 > 代码库 > 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