责任链模式(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;  
}
相关推荐
无聊的小坏坏6 分钟前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
YOLO大师35 分钟前
华为OD机试 2025B卷 - 小明减肥(C++&Python&JAVA&JS&C语言)
c++·python·华为od·华为od机试·华为od2025b卷·华为机试2025b卷·华为od机试2025b卷
看到我,请让我去学习2 小时前
OpenCV编程- (图像基础处理:噪声、滤波、直方图与边缘检测)
c语言·c++·人工智能·opencv·计算机视觉
xiaolang_8616_wjl11 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
夜月yeyue11 小时前
设计模式分析
linux·c++·stm32·单片机·嵌入式硬件
无小道11 小时前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++
FirstFrost --sy13 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Tanecious.13 小时前
C++--map和set的使用
开发语言·c++
Yingye Zhu(HPXXZYY)14 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
liulilittle15 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表