C++ Chain of Responsibility Pattern Example

In this article, we will learn how to use and implement the Chain of Responsibility Pattern in C++ with an example.

Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.

C++ Chain of Responsibility Pattern Example

The below diagram shows the generic structure of the Chain of Responsibility Pattern:

Let's refer to the above structure to create an example to demonstrates the usage of the Chain of Responsibility Pattern.
#include <iostream>

/*
 * Handler
 * defines an interface for handling requests and
 * optionally implements the successor link
 */
class Handler
{
public:
    virtual ~Handler() {}

    virtual void setHandler( Handler *s )
    {
        successor = s;
    }

    virtual void handleRequest()
    {
        if (successor != 0)
        {
            successor->handleRequest();
        }
    }

private:
    Handler *successor;
};

/*
 * Concrete Handlers
 * handle requests they are responsible for
 */
class ConcreteHandler1 : public Handler
{
public:
    ~ConcreteHandler1() {}

    bool canHandle()
    {
        return false;
    }

    virtual void handleRequest()
    {
        if ( canHandle() )
        {
            std::cout << "Handled by Concrete Handler 1" << std::endl;
        }
        else
        {
            std::cout << "Cannot be handled by Handler 1" << std::endl;
            Handler::handleRequest();
        }
    }
};

class ConcreteHandler2 : public Handler
{
public:
    ~ConcreteHandler2() {}

    bool canHandle()
    {
        return true;
    }

    virtual void handleRequest()
    {
        if ( canHandle() )
        {
            std::cout << "Handled by Handler 2" << std::endl;
        }
        else
        {
            std::cout << "Cannot be handled by Handler 2" << std::endl;
            Handler::handleRequest();
        }
    }
};


int main()
{
    ConcreteHandler1 handler1;
    ConcreteHandler2 handler2;

    handler1.setHandler( &handler2 );
    handler1.handleRequest();

    return 0;
}

Output

Cannot be handled by Handler 1
Handled by Handler 2

When to Use Chain of Responsibility Pattern

  • Use the Chain of Responsibility pattern when your program is expected to process different kinds of requests in various ways, but the exact types of requests and their sequences are unknown beforehand.
  • Use the pattern when it’s essential to execute several handlers in a particular order.
  • Use the CoR pattern when the set of handlers and their order are supposed to change at runtime.

Related C++ Design Patterns

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course