职责链模式——大话设计模式读书笔记

职责链模式(Chain of Responsibility): 使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个请求连城一个链,并沿着这条链传递该请求,知道一个对象处理它为止。

下面是职责链模式的UML图:

Main

下面是C++实现的代码:

/*
 * Copyright (c) 2017 initm.com All rights reserved.
 * 作者: Stupid
 * 描述: 职责链模式
 * 完成时间: 2017-12-03 16:13
*/

#include <QCoreApplication>
#include <iostream>
#include <cstdlib>

class Handler
{
protected:
    Handler* successor = nullptr;

public:
    void SetSuccessor(Handler* successor){
        this->successor = successor;
    }
    virtual void HandleRequest(const int& request) = 0;
    virtual ~Handler(){}
};

template <int N>
class ConcreteHandler: public Handler
{
public:
    void HandleRequest(const int& request)override final{
        if(request >= 10*(N-1) && request < 10*N){
            std::cout << "ConcreteHandler" << N << " 处理请求" << request << std::endl;
        }else if(nullptr != successor){
            successor->HandleRequest(request);
        }
    }
};

int main(int argc, char *argv[])
{
    system("chcp 65001");
    QCoreApplication a(argc, argv);

    Handler* handler1 = new ConcreteHandler<1>;
    Handler* handler2 = new ConcreteHandler<2>;
    Handler* handler3 = new ConcreteHandler<3>;
    handler1->SetSuccessor(handler2);
    handler2->SetSuccessor(handler3);

    int requests[] = {2, 5, 14, 22, 18, 3, 27, 20};

    for(auto i : requests){
        handler1->HandleRequest(i);
    }

    return a.exec();
}

职责链模式类似于DNS服务器,如果本级找不到对应的处理方式,那么就让更高级去处理。

发表回复

您的电子邮箱地址不会被公开。