大话设计模式之职责链模式

职责链模式是一种行为型设计模式,它允许多个对象共同处理请求,从而避免请求的发送者和接收者之间的耦合关系。在职责链模式中,请求沿着一个链传递,直到有一个对象能够处理它为止。

职责链模式主要由以下几个角色组成:

  • 处理者(Handler):定义处理请求的接口,并维护一个后继处理者的引用。
  • 具体处理者(Concrete Handler):实现处理请求的接口,并决定是否处理请求,以及是否将请求传递给下一个处理者。
  • 客户端(Client):创建请求,并将它们发送给第一个处理者。
cpp 复制代码
#include <iostream>
#include <string>

// 处理者抽象类
class Handler {
public:
    virtual ~Handler() {}
    virtual void handleRequest(const std::string& request) = 0;
    void setSuccessor(Handler* successor) {
        successor_ = successor;
    }

protected:
    Handler* successor_;
};

// 具体处理者 A
class ConcreteHandlerA : public Handler {
public:
    void handleRequest(const std::string& request) override {
        if (request == "A") {
            std::cout << "Concrete Handler A handled the request." << std::endl;
        } else if (successor_) {
            successor_->handleRequest(request);
        }
    }
};

// 具体处理者 B
class ConcreteHandlerB : public Handler {
public:
    void handleRequest(const std::string& request) override {
        if (request == "B") {
            std::cout << "Concrete Handler B handled the request." << std::endl;
        } else if (successor_) {
            successor_->handleRequest(request);
        }
    }
};

// 具体处理者 C
class ConcreteHandlerC : public Handler {
public:
    void handleRequest(const std::string& request) override {
        if (request == "C") {
            std::cout << "Concrete Handler C handled the request." << std::endl;
        } else if (successor_) {
            successor_->handleRequest(request);
        }
    }
};

int main() {
    // 创建具体处理者对象
    ConcreteHandlerA handlerA;
    ConcreteHandlerB handlerB;
    ConcreteHandlerC handlerC;

    // 设置处理者之间的关系
    handlerA.setSuccessor(&handlerB);
    handlerB.setSuccessor(&handlerC);

    // 发送请求
    handlerA.handleRequest("A"); // Concrete Handler A handled the request.
    handlerA.handleRequest("B"); // Concrete Handler B handled the request.
    handlerA.handleRequest("C"); // Concrete Handler C handled the request.
    handlerA.handleRequest("D"); // No handler can handle the request.

    return 0;
}

/*
在这个示例中,Handler 是处理请求的抽象类,定义了一个纯虚函数 handleRequest() 用于处理请求,
并维护了一个后继处理者的指针。ConcreteHandlerA、ConcreteHandlerB 和 ConcreteHandlerC 是具体处理者,
分别表示处理请求的具体实现。在 main() 函数中,我们创建了具体处理者对象,并设置了它们之间的关系,
然后依次向第一个处理者发送请求,直到有一个处理者能够处理为止。
*/

觉得有帮助的话,打赏一下呗。。

相关推荐
蝸牛ちゃん1 分钟前
设计模式(十六)行为型:解释器模式详解
设计模式·系统架构·解释器模式·软考高级
蝸牛ちゃん4 小时前
设计模式(二十二)行为型:策略模式详解
设计模式·系统架构·软考高级·策略模式
蝸牛ちゃん6 小时前
设计模式(六)创建型:单例模式详解
单例模式·设计模式·系统架构·软考高级
易元9 小时前
设计模式-访问者模式
前端·后端·设计模式
IT小白架构师之路11 小时前
常用设计模式系列(十五)—解释器模式
设计模式·解释器模式
蝸牛ちゃん11 小时前
设计模式(二十三)行为型:模板方法模式详解
设计模式·系统架构·软考高级·模板方法模式
蝸牛ちゃん11 小时前
设计模式(十七)行为型:迭代器模式详解
设计模式·系统架构·迭代器模式·软考高级
蝸牛ちゃん11 小时前
设计模式(十五)行为型:命令模式详解
设计模式·系统架构·软考高级·命令模式
蝸牛ちゃん1 天前
设计模式(七)结构型:适配器模式详解
设计模式·系统架构·软考高级·适配器模式
蝸牛ちゃん1 天前
设计模式(十二)结构型:享元模式详解
设计模式·系统架构·软考高级·享元模式