责任链模式

#include <iostream>

using namespace std;

class Handler
{
private:
    int mMsg;
    Handler *mNextHandler;
public:
    Handler(int msg) :mMsg(msg), mNextHandler(NULL) {}
    ~Handler() {}
public:
    virtual void handleMessage(int message) = 0;

    int getMessage()
    {
        return mMsg;
    }

    Handler *getNextHandler()
    {
        return mNextHandler;
    }

    void setNextHandler(Handler *handler)
    {
        mNextHandler = handler;
    }
};

class MouseHandler : public Handler
{
public:
    MouseHandler(int msg) :Handler(msg) {}
    ~MouseHandler() {}
public:
    virtual void handleMessage(int message)
    {
        cout << "MouseHandler handled the message : " << message << endl;
    }
};

class CatHandler : public Handler
{
public:
    CatHandler(int msg) :Handler(msg) {}
    ~CatHandler() {}
public:
    virtual void handleMessage(int message)
    {
        cout << "CatHandler handled the message : " << message << endl;
    }
};

class DogHandler : public Handler
{
public:
    DogHandler(int msg) :Handler(msg) {}
    ~DogHandler() {}
public:
    virtual void handleMessage(int message)
    {
        cout << "DogHandler handled the message : " << message << endl;
    }
};

void looper(int message, Handler *handler)
{
    Handler *temp = handler;

    while (true)
    {
        if (temp->getMessage() == message)
        {
            temp->handleMessage(message);
            break;
        }
        else if (temp->getMessage() == 0)
        {
            temp->handleMessage(message);
            break;
        }
        else
        {
            if (temp->getNextHandler() != NULL)
            {
                temp = temp->getNextHandler();
            }
            else
            {
                cout << "no handler!" << endl;
                break;
            }
        }
    }
}

int main(int argc, char const *argv[])
{
    Handler *mouseHandler = new MouseHandler(1);
    Handler *catHandler = new CatHandler(2);
    Handler *dogHandler = new DogHandler(0);

    mouseHandler->setNextHandler(catHandler);
    catHandler->setNextHandler(dogHandler);

    looper(2, mouseHandler);
    looper(-1, mouseHandler);

    delete dogHandler;
    dogHandler = NULL;

    delete catHandler;
    catHandler = NULL;

    delete mouseHandler;
    mouseHandler = NULL;

    return 0;
}

 

posted @ 2018-10-11 16:30  c&z  阅读(124)  评论(0编辑  收藏  举报