责任链模式(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;  
}
相关推荐
肆忆_15 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星19 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马4 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼5 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛