Example of Chain of Responsibility Design Pattern in C++

Problem Statement:

Suppose we have to handle authentication requests with a chain of handlers. Depending on the type of authentication request, the appropriate handler in the chain handles it, or it is passed along the chain until a handler can process it or until the end of the chain is reached.

Implementation of Chain of Responsibility Pattern in C++:

AuthenticationHandler (Handler Interface):

This is an abstract base class that defines the interface for all authentication handlers. It declares two pure virtual functions:

  • setNextHandler(AuthenticationHandler* handler): This function allows setting the next handler in the chain.
  • handleRequest(const std::string& request): This function is responsible for handling authentication requests.

Below is the implementation of the above function:

C++




// Handler Interface
class AuthenticationHandler {
public:
    virtual void
    setNextHandler(AuthenticationHandler* handler)
        = 0;
    virtual void handleRequest(const std::string& request)
        = 0;
};


Concrete Handlers:

Two concrete handler classes are defined:

1. UsernamePasswordHandler: This handler checks if the authentication request is for “username_password.” If it is, it prints a message indicating successful authentication using a username and password. If the request is not for “username_password,” it forwards the request to the next handler in the chain, if available. If there is no next handler, it prints a message indicating an invalid authentication method.

Below is the implementation of the above function:

C++




// Concrete Handlers
class UsernamePasswordHandler
    : public AuthenticationHandler {
private:
    AuthenticationHandler* nextHandler;
 
public:
    void
    setNextHandler(AuthenticationHandler* handler) override
    {
        nextHandler = handler;
    }
 
    void handleRequest(const std::string& request) override
    {
        if (request == "username_password") {
            std::cout << "Authenticated using username and "
                         "password."
                      << std::endl;
        }
        else if (nextHandler != nullptr) {
            nextHandler->handleRequest(request);
        }
        else {
            std::cout << "Invalid authentication method."
                      << std::endl;
        }
    }
};


2. OAuthHandler: This handler checks if the authentication request is for “oauth_token.” If it is, it prints a message indicating successful authentication using an OAuth token. If the request is not for “oauth_token,” it forwards the request to the next handler in the chain, if available. If there is no next handler, it prints a message indicating an invalid authentication method.

C++




class OAuthHandler : public AuthenticationHandler {
private:
    AuthenticationHandler* nextHandler;
 
public:
    void setNextHandler(AuthenticationHandler* handler) override {
        nextHandler = handler;
    }
 
    void handleRequest(const std::string& request) override {
        if (request == "oauth_token") {
            std::cout << "Authenticated using OAuth token." << std::endl;
        } else if (nextHandler != nullptr) {
            nextHandler->handleRequest(request);
        } else {
            std::cout << "Invalid authentication method." << std::endl;
        }
    }
};


Note: In the main function, two instances of the concrete handlers are created: usernamePasswordHandler and oauthHandler.

Main Function:

Three authentication requests are made using handleRequest:

  • First, an “oauth_token” request is sent. The request is successfully handled by the oauthHandler.
  • Second, a “username_password” request is sent. This time, the request is successfully handled by the usernamePasswordHandler.
  • Third, an “invalid_method” request is sent. None of the handlers in the chain can handle this request, so an “Invalid authentication method” message is printed.

Below is the implementation of the above function:

C++




int main()
{
    AuthenticationHandler* usernamePasswordHandler
        = new UsernamePasswordHandler();
    AuthenticationHandler* oauthHandler
        = new OAuthHandler();
 
    // Set up the chain
    usernamePasswordHandler->setNextHandler(oauthHandler);
 
    // Handling authentication requests
    usernamePasswordHandler->handleRequest("oauth_token");
    usernamePasswordHandler->handleRequest(
        "username_password");
    usernamePasswordHandler->handleRequest(
        "invalid_method");
 
    delete usernamePasswordHandler;
    delete oauthHandler;
 
    return 0;
}


Below is the complete combined code of the above example:

C++




#include <iostream>
#include <string>
 
// Handler Interface
class AuthenticationHandler {
public:
    virtual void
    setNextHandler(AuthenticationHandler* handler)
        = 0;
    virtual void handleRequest(const std::string& request)
        = 0;
};
 
// Concrete Handlers
class UsernamePasswordHandler
    : public AuthenticationHandler {
private:
    AuthenticationHandler* nextHandler;
 
public:
    void
    setNextHandler(AuthenticationHandler* handler) override
    {
        nextHandler = handler;
    }
 
    void handleRequest(const std::string& request) override
    {
        if (request == "username_password") {
            std::cout << "Authenticated using username and "
                         "password."
                      << std::endl;
        }
        else if (nextHandler != nullptr) {
            nextHandler->handleRequest(request);
        }
        else {
            std::cout << "Invalid authentication method."
                      << std::endl;
        }
    }
};
 
class OAuthHandler : public AuthenticationHandler {
private:
    AuthenticationHandler* nextHandler;
 
public:
    void
    setNextHandler(AuthenticationHandler* handler) override
    {
        nextHandler = handler;
    }
 
    void handleRequest(const std::string& request) override
    {
        if (request == "oauth_token") {
            std::cout << "Authenticated using OAuth token."
                      << std::endl;
        }
        else if (nextHandler != nullptr) {
            nextHandler->handleRequest(request);
        }
        else {
            std::cout << "Invalid authentication method."
                      << std::endl;
        }
    }
};
 
// Client
int main()
{
    AuthenticationHandler* usernamePasswordHandler
        = new UsernamePasswordHandler();
    AuthenticationHandler* oauthHandler
        = new OAuthHandler();
 
    // Set up the chain
    usernamePasswordHandler->setNextHandler(oauthHandler);
 
    // Handling authentication requests
    usernamePasswordHandler->handleRequest("oauth_token");
    usernamePasswordHandler->handleRequest(
        "username_password");
    usernamePasswordHandler->handleRequest(
        "invalid_method");
 
    delete usernamePasswordHandler;
    delete oauthHandler;
 
    return 0;
}


Output

Authenticated using OAuth token.
Authenticated using username and password.
Invalid authentication method.


Key Component of Chain of Responsibility Design Pattern in C++

The Chain of Responsibility Pattern consists of the following key components:

  • Handler Interface or Abstract Class: This is the base class that defines the interface for handling requests and, in many cases, for chaining to the next handler in the sequence.
  • Concrete Handlers: These are the classes that implement how the requests are going to be handled. They can handle the request or pass it to the next handler in the chain if it is unable to handle that request.
  • Client: The request is sent by the client, who then forwards it to the chain’s first handler. Which handler will finally handle the request is unknown to the client.

Diagrammatical Representation of the Example

Diagrammatical Representation of Authentication Handling with Chain of Responsibility Pattern in C++.

  • Setting up the Interface: The code begins with the definition of an abstract class, “AuthenticationHandler”, which sets the guidelines for handling different authentication requests. It declares two virtual functions:
  • Implementing Concrete Handlers: There are Two concrete classes namely “UsernamePasswordHandler” and “OAuthHandler”, implementing the “AuthenticationHandler” interface. Each of these handlers processes a specific type of authentication request.
  • Setting up the Client Code: The “main” function serves as the client code in this example.

The example effectively demonstrates the Chain of Responsibility pattern, where different authentication handlers are linked together to handle specific types of requests, providing a flexible and decoupled approach to authentication processing.

Chain of Responsibility Method Design Patterns in C++

Chain of responsibility Pattern or Chain of Responsibility Method is a behavioral pattern, which allows an object to send a request to other objects without knowing who is going to handle it. This pattern is frequently used in the chain of multiple objects, where each object either handles the request or passes it on to the next object in the chain if it is unable to handle that request. This pattern encourages loose coupling between sender and receiver, providing freedom in how the request is handled.

Important Topics for the Chain of Responsibility Method Design Patterns in C++

  • Example of Chain of Responsibility Design Pattern in C++
  • Advantages of the Chain of Responsibility Pattern in C++
  • Disadvantages of the Chain of Responsibility Pattern in C++
  • Conclusion:

Similar Reads

Example of Chain of Responsibility Design Pattern in C++

Problem Statement:...

Advantages of the Chain of Responsibility Pattern in C++

...

Disadvantages of the Chain of Responsibility Pattern in C++

...

Conclusion

...