C++中的责任链模式

目录

[责任链模式(Chain of Responsibility Pattern)](#责任链模式(Chain of Responsibility Pattern))

实际应用

日志记录器

技术支持系统

审批流程系统

总结


责任链模式(Chain of Responsibility Pattern)

责任链模式是一种行为设计模式,它允许多个对象有机会处理请求,从而避免请求的发送者与接收者之间的耦合。这些对象被连接成一条链,沿着这条链传递请求,直到有一个对象处理它为止。

实际应用

日志记录器

用责任链模式来创建一系列日志记录器,每个记录器处理特定级别的日志信息,并将其传递给下一个记录器。

cpp 复制代码
#include <iostream>
#include <memory>

// 日志级别
enum LogLevel {
    INFO,
    WARNING,
    ERROR
};

// 抽象的日志处理器
class Logger {
protected:
    std::shared_ptr<Logger> next;
public:
    Logger() : next(nullptr) {}
    void setNext(std::shared_ptr<Logger> nextLogger) {
        next = nextLogger;
    }
    void logMessage(LogLevel level, const std::string& message) {
        if (this->canHandle(level)) {
            this->write(message);
        }
        if (next) {
            next->logMessage(level, message);
        }
    }
    virtual bool canHandle(LogLevel level) = 0;
    virtual void write(const std::string& message) = 0;
};

// 具体的日志处理器:信息日志处理器
class InfoLogger : public Logger {
public:
    bool canHandle(LogLevel level) override {
        return level == INFO;
    }
    void write(const std::string& message) override {
        std::cout << "InfoLogger: " << message << "\n";
    }
};

// 具体的日志处理器:警告日志处理器
class WarningLogger : public Logger {
public:
    bool canHandle(LogLevel level) override {
        return level == WARNING;
    }
    void write(const std::string& message) override {
        std::cout << "WarningLogger: " << message << "\n";
    }
};

// 具体的日志处理器:错误日志处理器
class ErrorLogger : public Logger {
public:
    bool canHandle(LogLevel level) override {
        return level == ERROR;
    }
    void write(const std::string& message) override {
        std::cout << "ErrorLogger: " << message << "\n";
    }
};

int main() {
    auto errorLogger = std::make_shared<ErrorLogger>();
    auto warningLogger = std::make_shared<WarningLogger>();
    auto infoLogger = std::make_shared<InfoLogger>();

    infoLogger->setNext(warningLogger);
    warningLogger->setNext(errorLogger);

    infoLogger->logMessage(INFO, "This is an information.");
    infoLogger->logMessage(WARNING, "This is a warning.");
    infoLogger->logMessage(ERROR, "This is an error.");

    return 0;
}

技术支持系统

用责任链模式来创建一系列处理器,每个处理器处理特定级别的客户请求,并将其传递给下一个处理器。

cpp 复制代码
#include <iostream>
#include <memory>

// 请求级别
enum RequestLevel {
    GENERAL,
    TECHNICAL,
    ADVANCED_TECHNICAL
};

// 抽象的请求处理器
class SupportHandler {
protected:
    std::shared_ptr<SupportHandler> next;
public:
    SupportHandler() : next(nullptr) {}
    void setNext(std::shared_ptr<SupportHandler> nextHandler) {
        next = nextHandler;
    }
    void handleRequest(RequestLevel level, const std::string& request) {
        if (this->canHandle(level)) {
            this->process(request);
        } else if (next) {
            next->handleRequest(level, request);
        }
    }
    virtual bool canHandle(RequestLevel level) = 0;
    virtual void process(const std::string& request) = 0;
};

// 具体的请求处理器:一般请求处理器
class GeneralSupportHandler : public SupportHandler {
public:
    bool canHandle(RequestLevel level) override {
        return level == GENERAL;
    }
    void process(const std::string& request) override {
        std::cout << "GeneralSupportHandler: Processing " << request << "\n";
    }
};

// 具体的请求处理器:技术请求处理器
class TechnicalSupportHandler : public SupportHandler {
public:
    bool canHandle(RequestLevel level) override {
        return level == TECHNICAL;
    }
    void process(const std::string& request) override {
        std::cout << "TechnicalSupportHandler: Processing " << request << "\n";
    }
};

// 具体的请求处理器:高级技术请求处理器
class AdvancedTechnicalSupportHandler : public SupportHandler {
public:
    bool canHandle(RequestLevel level) override {
        return level == ADVANCED_TECHNICAL;
    }
    void process(const std::string& request) override {
        std::cout << "AdvancedTechnicalSupportHandler: Processing " << request << "\n";
    }
};

int main() {
    auto advancedHandler = std::make_shared<AdvancedTechnicalSupportHandler>();
    auto technicalHandler = std::make_shared<TechnicalSupportHandler>();
    auto generalHandler = std::make_shared<GeneralSupportHandler>();

    generalHandler->setNext(technicalHandler);
    technicalHandler->setNext(advancedHandler);

    generalHandler->handleRequest(GENERAL, "General Inquiry");
    generalHandler->handleRequest(TECHNICAL, "Technical Issue");
    generalHandler->handleRequest(ADVANCED_TECHNICAL, "Advanced Technical Problem");

    return 0;
}

审批流程系统

用责任链模式来创建一系列处理器,每个处理器处理特定级别的审批请求,并将其传递给下一个处理器。

cpp 复制代码
#include <iostream>
#include <memory>

// 审批级别
enum ApprovalLevel {
    DEPARTMENT_MANAGER,
    GENERAL_MANAGER,
    BOARD
};

// 抽象的审批处理器
class Approver {
protected:
    std::shared_ptr<Approver> next;
public:
    Approver() : next(nullptr) {}
    void setNext(std::shared_ptr<Approver> nextApprover) {
        next = nextApprover;
    }
    void approveRequest(ApprovalLevel level, const std::string& request) {
        if (this->canApprove(level)) {
            this->approve(request);
        } else if (next) {
            next->approveRequest(level, request);
        }
    }
    virtual bool canApprove(ApprovalLevel level) = 0;
    virtual void approve(const std::string& request) = 0;
};

// 具体的审批处理器:部门经理
class DepartmentManager : public Approver {
public:
    bool canApprove(ApprovalLevel level) override {
        return level == DEPARTMENT_MANAGER;
    }
    void approve(const std::string& request) override {
        std::cout << "DepartmentManager: Approving " << request << "\n";
    }
};

// 具体的审批处理器:总经理
class GeneralManager : public Approver {
public:
    bool canApprove(ApprovalLevel level) override {
        return level == GENERAL_MANAGER;
    }
    void approve(const std::string& request) override {
        std::cout << "GeneralManager: Approving " << request << "\n";
    }
};

// 具体的审批处理器:董事会
class Board : public Approver {
public:
    bool canApprove(ApprovalLevel level) override {
        return level == BOARD;
    }
    void approve(const std::string& request) override {
        std::cout << "Board: Approving " << request << "\n";
    }
};

int main() {
    auto board = std::make_shared<Board>();
    auto generalManager = std::make_shared<GeneralManager>();
    auto departmentManager = std::make_shared<DepartmentManager>();

    departmentManager->setNext(generalManager);
    generalManager->setNext(board);

    departmentManager->approveRequest(DEPARTMENT_MANAGER, "Budget Approval");
    departmentManager->approveRequest(GENERAL_MANAGER, "Project Approval");
    departmentManager->approveRequest(BOARD, "Company Merger Approval");

    return 0;
}

总结

责任链模式在实际项目中可以帮助我们将请求的发送者与接收者解耦,并沿着处理器链传递请求,直到有一个处理器处理它。

相关推荐
小_太_阳16 分钟前
Scala_【2】变量和数据类型
开发语言·后端·scala·intellij-idea
直裾18 分钟前
scala借阅图书保存记录(三)
开发语言·后端·scala
唐 城39 分钟前
curl 放弃对 Hyper Rust HTTP 后端的支持
开发语言·http·rust
码银2 小时前
【python】银行客户流失预测预处理部分,独热编码·标签编码·数据离散化处理·数据筛选·数据分割
开发语言·python
从善若水2 小时前
【2024】Merry Christmas!一起用Rust绘制一颗圣诞树吧
开发语言·后端·rust
lqqjuly3 小时前
特殊的“Undefined Reference xxx“编译错误
c语言·c++
冰红茶兑滴水3 小时前
云备份项目--工具类编写
linux·c++
刘好念3 小时前
[OpenGL]使用 Compute Shader 实现矩阵点乘
c++·计算机图形学·opengl·glsl
2401_858286113 小时前
115.【C语言】数据结构之排序(希尔排序)
c语言·开发语言·数据结构·算法·排序算法
Jelena技术达人4 小时前
Java爬虫获取1688关键字 item_search接口返回值详细解析
java·开发语言·爬虫