[行为型模式]命令模式的理解




头文件
//CommandPattern.h

#ifndef COMMAND_PATTERN_H
#define COMMAND_PATTERN_H

#include <Windows.h>
#include <string>
using namespace std;


namespace CommandPattern
{

class Receiver
{
public:
    void Action();
};

class AbstructCommand
{
public:
    virtual ~AbstructCommand();
    virtual void Execute() = 0;
};

class ConcretetCommand : public AbstructCommand
{
public:
    ConcretetCommand(Receiver* pReciver);
    virtual ~ConcretetCommand();
    virtual void Execute();

private:
    Receiver* m_pReciver;
};


class Invoker
{
public:
    Invoker(AbstructCommand* pCommand);

    void Order();

private:
    AbstructCommand* m_pCommand;
};

//////////////////////////////////////////////////////////////////////////
void CommandPattern_Test();
}

#endif

实现
#include "CommandPattern.h"
#include <iostream>
using namespace std;

#define SAFE_DELETE(p) if (p) { delete p; p = NULL; }

namespace CommandPattern
{
    //////////////////////////////////////////////////////////////////////////
     void Receiver::Action()
     {
         cout << "Receiver->Action" << endl;
     }

     //////////////////////////////////////////////////////////////////////////
     AbstructCommand::~AbstructCommand()
     {

     }

    //////////////////////////////////////////////////////////////////////////
    ConcretetCommand::ConcretetCommand(Receiver* pReciver)
        : m_pReciver(NULL)
    {
        if (m_pReciver==NULL && pReciver!=NULL)
        {
            m_pReciver = pReciver;
        }
    }
     
    ConcretetCommand::~ConcretetCommand()
    {

    }

    void ConcretetCommand::Execute()
    {
        if (m_pReciver != NULL)
        {
            cout << "ConcretetCommand->Execute" << endl;
            m_pReciver->Action();
        }
    }

    //////////////////////////////////////////////////////////////////////////
    Invoker::Invoker(AbstructCommand* pCommand)
        : m_pCommand(NULL)
    {
        if (m_pCommand==NULL && pCommand!=NULL)
        {
            m_pCommand = pCommand;
        }
    }

    void Invoker::Order()
    {
        cout << "Invoker->Order" << endl;
        m_pCommand->Execute();
    }


    void CommandPattern_Test()
    {
        Receiver* pReceiver = new Receiver();
        ConcretetCommand* pConcreteCmd = new ConcretetCommand(pReceiver);
        Invoker* pInvoker= new Invoker(pConcreteCmd);

        pInvoker->Order();

        SAFE_DELETE(pReceiver);
        SAFE_DELETE(pConcreteCmd);
        SAFE_DELETE(pInvoker);
    }
}

客户端
#include "CommandPattern.h"


#include <iostream>
using namespace std;
using namespace CommandPattern;
void main()
{
    CommandPattern_Test();
}

运行结果
Invoker->Order
ConcretetCommand->Execute
Receiver->Action


猜你喜欢

转载自jacky-dai.iteye.com/blog/2306606
今日推荐