责任链模式(C++)

**定义:**责任链模式(Chain of Responsibility)是一种行为设计模式,它允许你将请求沿着处理者链进行传递。每个处理者都有机会处理请求,如果某个处理者不能处理该请求,则可以将请求传递给链中的下一个处理者。这个模式使得你可以在不修改现有代码结构的情况下,动态地添加或删除处理者,并且可以将请求和处理者解耦,使得请求可以发送给一系列的处理者而无需关心哪个处理者会实际处理它。

代码:

cpp 复制代码
// 抽象处理者  
class Handler {  
public:  
    virtual ~Handler() = default;  
    // 设置下一个处理者  
    void setNext(std::shared_ptr<Handler> next) {  
        this->nextHandler = next;  
    }  
    // 处理请求  
    void handleRequest(const std::string& request) {  
        if (canHandle(request)) {  
            handle(request);  
        } else if (nextHandler) {  
            nextHandler->handleRequest(request);  
        } else {  
            std::cout << "No handler could process the request: " << request << std::endl;  
        }  
    }  
  
protected:  
    // 判断是否能处理请求  
    virtual bool canHandle(const std::string& request) const = 0;  
    // 处理请求的具体实现  
    virtual void handle(const std::string& request) = 0;  
  
private:  
    std::shared_ptr<Handler> nextHandler;  
};  
  
// 具体处理者A  
class ConcreteHandlerA : public Handler {  
protected:  
    bool canHandle(const std::string& request) const override {  
        return request == "RequestA";  
    }  
    void handle(const std::string& request) override {  
        std::cout << "ConcreteHandlerA handled request: " << request << std::endl;  
    }  
};  
  
// 具体处理者B  
class ConcreteHandlerB : public Handler {  
protected:  
    bool canHandle(const std::string& request) const override {  
        return request == "RequestB";  
    }  
    void handle(const std::string& request) override {  
        std::cout << "ConcreteHandlerB handled request: " << request << std::endl;  
    }  
};  
  
int main() {  
    // 创建处理者  
    auto handlerA = std::make_shared<ConcreteHandlerA>();  
    auto handlerB = std::make_shared<ConcreteHandlerB>();  
  
    // 设置职责链  
    handlerA->setNext(handlerB);  
  
    // 发送请求  
    handlerA->handleRequest("RequestA"); // ConcreteHandlerA handled request: RequestA  
    handlerA->handleRequest("RequestB"); // ConcreteHandlerB handled request: RequestB  
    handlerA->handleRequest("RequestC"); // No handler could process the request: RequestC  
  
    return 0;  
}
相关推荐
Bella的成长园地5 小时前
面试中关于 c++ async 的高频面试问题有哪些?
c++·面试
彷徨而立5 小时前
【C/C++】什么是 运行时库?运行时库 /MT 和 /MD 的区别?
c语言·c++
qq_417129256 小时前
C++中的桥接模式变体
开发语言·c++·算法
No0d1es8 小时前
电子学会青少年软件编程(C语言)等级考试试卷(三级)2025年12月
c语言·c++·青少年编程·电子学会·三级
bjxiaxueliang9 小时前
一文掌握C/C++命名规范:风格、规则与实践详解
c语言·开发语言·c++
xu_yule10 小时前
网络和Linux网络-13(高级IO+多路转接)五种IO模型+select编程
linux·网络·c++·select·i/o
2301_7657031410 小时前
C++与自动驾驶系统
开发语言·c++·算法
轩情吖10 小时前
Qt的窗口(三)
c++·qt
热爱编程的小刘10 小时前
Lesson04---类与对象(下篇)
开发语言·c++·算法
郝学胜-神的一滴10 小时前
Linux网络编程之listen函数:深入解析与应用实践
linux·服务器·开发语言·网络·c++·程序人生