Chain of Responsibility Method Design Patterns in C++
Last Updated :
06 Nov, 2023
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++
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++
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++
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();
usernamePasswordHandler->setNextHandler(oauthHandler);
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>
class AuthenticationHandler {
public :
virtual void
setNextHandler(AuthenticationHandler* handler)
= 0;
virtual void handleRequest( const std::string& request)
= 0;
};
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;
}
}
};
int main()
{
AuthenticationHandler* usernamePasswordHandler
= new UsernamePasswordHandler();
AuthenticationHandler* oauthHandler
= new OAuthHandler();
usernamePasswordHandler->setNextHandler(oauthHandler);
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.
Advantages of the Chain of Responsibility Pattern in C++
- Decoupling of Objects: The pattern makes enables sending a request to a series of possible recipients without having to worry about which object will handle it in the end. This lessens the reliance between items.
- Flexibility and Extensibility: New handlers can be easily added or existing ones can be modified without affecting the client code. This promotes flexibility and extensibility within the system.
- Dynamic Order of Handling: The sequence and order of handling requests can be changed dynamically during runtime, which allows adjustment of the processing logic as per the requirements.
- Simplified Object Interactions: It simplifies the interaction between the sender and receiver objects, as the sender does not need to know about the processing logic.
- Enhanced Maintainability: Each handler performs a specific type of processing, which making maintaining and modifying the individual components easier without impacting the overall system.
Disadvantages of the Chain of Responsibility Pattern in C++
- Possible Unhandled Requests: The chain should be implemented correctly otherwise there is a chance that some requests might not get handled at all, which leads to unexpected behavior in the application.
- Performance Overhead: The request will go through several handlers in the chain if it is lengthy and complicated, which could cause performance overhead. The processing logic of each handler has an effect on the system’s overall performance.
- Complexity in Debugging: The fact that the chain has several handlers can make debugging more difficult. Tracking the progression of a request and determining which handler is in charge of handling it can be difficult.
- Runtime Configuration Overhead: It may become more difficult to manage and maintain the chain of responsibility if the chain is dynamically modified at runtime.
Conclusion
In conclusion, the Chain of Responsibility pattern is a powerful tool for creating a flexible and extensible chain of handlers to process requests. It promotes loose coupling, making it a valuable addition to your design pattern toolbox when building C++ applications. However, like any design pattern, it should be used judiciously, considering the specific requirements of your application.
Share your thoughts in the comments
Please Login to comment...