美文网首页设计模式
Chain of Responsibility模式

Chain of Responsibility模式

作者: 老练子丶2017 | 来源:发表于2017-11-24 10:46 被阅读0次

    有合适的处理对象就处理,没有就给下一个

    这里简化了,有下一个就给下一个

    handle.h

    #ifndef _HANDLE_H

    #define _HANDLE_H

    #include <iostream>

    using namespace std;

    class Handle

    {

    public:

    virtual ~Handle() {

    }

    Handle() {

    }

    Handle(Handle* succ) : _succ(succ) {

    }

    virtual void HandleRequest()=0;

    public:

    Handle* _succ;

    };

    class ConcreteHandleA : public Handle

    {

    public:

    ConcreteHandleA() {

    }

    ~ConcreteHandleA() {

    }

    ConcreteHandleA(Handle* succ) : Handle(succ) {

    }

    void HandleRequest() {

    if (_succ != NULL) {

    _succ->HandleRequest();

    } else {

    cout << "ConcreteHandleA:HandleRequest" << endl;

    }

    }

    };

    class ConcreteHandleB : public Handle

    {

    public:

    ConcreteHandleB() {

    }

    ~ConcreteHandleB() {

    }

    ConcreteHandleB(Handle* succ) : Handle(succ) {

    }

    void HandleRequest() {

    if (_succ != NULL) {

    _succ->HandleRequest();

    } else {

    cout << "ConcreteHandleA:HandleRequest" << endl;

    }

    }

    };

    #endif // _HANDLE_H

    handle.cpp

    #include "handle.h"

    int main()

    {

    Handle* handleA = new ConcreteHandleA;

    Handle* handleB = new ConcreteHandleB(handleA);

    handleB->HandleRequest();

    return 0;

    }

    编译:make handle

    相关文章

      网友评论

        本文标题:Chain of Responsibility模式

        本文链接:https://www.haomeiwen.com/subject/rmuxbxtx.html