C++责任链模式(ChainOfResponsibility)

 C++
时间:

应用场景

1、有多个对象可以处理同一个请求,具体哪个对象处理该请求由运行时刻自动确定。
2、在不明确指定接收者的情况下,向多个对象中的一个提交一个请求。
3、可动态指定一组对象处理请求。

ChainOfResponsibility

  • Handle.h
#pragma cone

class Handle
{
    public:
        virtual ~Handle() { delete _succ; }
        virtual void HandleRequest() = 0;
        void SetSuccessor(Handle* succ) { _succ = succ; }
        Handle* GetSuccessor() { return _succ; }
    protected:
        Handle() { _succ = nullptr; }
        Handle(Handle* succ) { _succ = succ; }
    private:
        Handle* _succ;
};

class ConcreteHandleA : public Handle
{
    public:
        ConcreteHandleA();
        ~ConcreteHandleA();
        ConcreteHandleA(Handle* succ);
        void HandleRequest();
    protected:
    private:
};

class ConcreteHandleB : public Handle
{
    public:
        ConcreteHandleB();
        ~ConcreteHandleB();
        ConcreteHandleB(Handle* succ);
        void HandleRequest();
    protected:
    private:
};
  • Handle.cpp
#include<iostream>
#include"Handle.h"

using namespace std;


ConcreteHandleA::ConcreteHandleA()
{

}

ConcreteHandleA::~ConcreteHandleA()
{

}

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

}

void ConcreteHandleA::HandleRequest()
{
    if(this->GetSuccessor() != 0)
    {
        cout << "ConcreteHandleA 处理权交给后继节点......" << endl;
        this->GetSuccessor()->HandleRequest();
    }
    else
    {
        cout << "ConcreteHandleA 没有后继节点,自己处理......." << endl;
    }
}

ConcreteHandleB::ConcreteHandleB()
{

}

ConcreteHandleB::~ConcreteHandleB()
{

}

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

}

void ConcreteHandleB::HandleRequest()
{
    if(this->GetSuccessor() != 0)
    {
        cout << "ConcreteHandleB 处理权交给后继节点......" << endl;
        this->GetSuccessor()->HandleRequest();
    }
    else
    {
        cout << "ConcreteHandleB 没有后继节点,自己处理......." << endl;
    }
}
  • main.cpp
#include<iostream>
#include<stdio.h>
#include"Handle.h"

using namespace std;

int main(int argc, char* argv[])
{
    Handle* h1 = new ConcreteHandleA();
    Handle* h2 = new ConcreteHandleB();
    h1->SetSuccessor(h2);
    h1->HandleRequest();
    getchar();
    return 0;
}

0 评论