BehavioralC++verifiedVerified

Chain of Responsibility Pattern in C++

Passes a request along a chain of handlers, where each handler decides to process it or pass it to the next handler in the chain.

How to Implement the Chain of Responsibility Pattern in C++

1Step 1: Define the Handler interface

class Handler {
protected:
    std::unique_ptr<Handler> next_;
public:
    virtual ~Handler() = default;

    Handler* setNext(std::unique_ptr<Handler> next) {
        next_ = std::move(next);
        return next_.get();
    }

    virtual std::string handle(const std::string& request) {
        if (next_) return next_->handle(request);
        return "Unhandled: " + request;
    }
};

2Step 2: Concrete handlers

class AuthHandler : public Handler {
public:
    std::string handle(const std::string& request) override {
        if (request.find("auth") != std::string::npos)
            return "Handled by AuthHandler";
        return Handler::handle(request);
    }
};

class LogHandler : public Handler {
public:
    std::string handle(const std::string& request) override {
        std::cout << "Log: " << request << "\n";
        return Handler::handle(request);
    }
};

class DataHandler : public Handler {
public:
    std::string handle(const std::string& request) override {
        if (request.find("data") != std::string::npos)
            return "Handled by DataHandler";
        return Handler::handle(request);
    }
};

3Step 3: Build and use the chain

int main() {
    auto auth = std::make_unique<AuthHandler>();
    auto log  = std::make_unique<LogHandler>();
    auto data = std::make_unique<DataHandler>();

    auto* logPtr = auth->setNext(std::move(log));
    logPtr->setNext(std::move(data));

    std::cout << auth->handle("data request") << "\n";
    std::cout << auth->handle("auth request") << "\n";
    std::cout << auth->handle("unknown") << "\n";
}

Chain of Responsibility Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Chain of Responsibility Pattern in the Real World

Like a customer support escalation: your call starts with a front-line agent. If they can’t resolve it, they transfer you to a specialist. If the specialist can’t help, it goes to a manager. Each level either handles it or passes it up the chain.