码迷,mamicode.com
首页 > 其他好文 > 详细

Command

时间:2014-12-17 12:41:41      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   ar   io   color   os   sp   on   

#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

标签:des   style   blog   ar   io   color   os   sp   on   

原文地址:http://www.cnblogs.com/stanley198610281217/p/4169057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!