责任链模式(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;  
}
相关推荐
Tanecious.20 分钟前
C++--红黑树
开发语言·c++
tanyongxi663 小时前
C++ Map 和 Set 详解:从原理到实战应用
开发语言·c++
飒飒真编程3 小时前
C++类模板继承部分知识及测试代码
开发语言·c++·算法
救赎小恶魔5 小时前
C++11的整理笔记
c++·笔记
岁忧5 小时前
(LeetCode 面试经典 150 题 ) 209. 长度最小的子数组(双指针)
java·c++·算法·leetcode·面试·go
小何好运暴富开心幸福5 小时前
分层架构的C++高并发内存池性能优化
c++·性能优化·架构
汉克老师6 小时前
GESP2025年6月认证C++三级( 第三部分编程题(1)奇偶校验)
c++·gesp三级·gesp3级
教练、我想打篮球6 小时前
68 指针的减法操作
c++·c·struct
Mr_Xuhhh6 小时前
QWidget的属性
java·数据库·c++·qt·系统架构
sun0077006 小时前
C++实现二叉树左右子树交换算法
开发语言·c++·算法