Chain of Responsibility Pattern – C++

So you are alone in your cubicle at work, twiddling away on your computer when suddenly your supervisor comes by and yells at you for not handing in some kind of report. You tried to do it earlier but your supervisor was too busy playing fuse ball with the VPs to listen to you. After all, miracle workers like you are suppose to work miracles, not bother the management. So now that the supervisor got chewed out for not having the status of his projects ready for the CIO you are going to hear about it. As the adage goes, “sh*t falls down hill”. The CIO chewed out the supervisor and that supervisor is going to pass the buck on to you since you are the one that can handle it. The working world is full of chains of responsibility. This pattern is part of nature and part of system design… we take a look at it through the world of C++ coming up here on the Programming Underground!

Yeah so your supervisor is taking advantage of the chain of responsibility set up in the company. Being the no named miracle worker programmer you are the one that no one understands but everyone knows you are some how important to the company. Besides… the supervisor needs someone to blame so they pass that on down the chain and that link is you!

If you are unfamiliar with design patterns, they are patterns that continue to pop up in all kinds of systems (natural as well as man made). The office analogy is how this pattern pops up in the real world. In the software world there may be various classes that each handle a specific task linked together in single file or making sure that only one instance of a resource is created at any one time (the singleton pattern).

The thing about design patterns are that once you have identified a situation where a pattern is emerging you can easily refactor your code into the pattern and make it more solid. The other thing nice about design patterns is that they are not language specific. While our example here is in C++, you could easily take the idea of the pattern and write it in python or vb or JavaScript or whatever.

In the chain of responsibility pattern when a request comes in the first class looks at the request, asks “can I handle this?” and if the answer is “no” it passes it on down the line hoping someone in the chain can handle it. Each class instance in the chain repeats the process and may pass it on down further.

Our example shows a series of three handler classes. Each one is called a specialHandler and it is derived from an abstract base class we simply call “Handler”. We will chain these three handlers together and give the chain some requests. The request will go through each instance until it can be handled or until it hits the end of the chain. In this case we will simply spit out a message saying that we were the last in the chain and couldn’t handle the request.

Now if you have been programming awhile you may think of this as something similar to a linked list. In a way it is and in a way it isn’t. With a chain of responsibility pattern we could potentially have various kinds of “handlers” in the setup and we might typically do more evaluation of the requests coming in than a node might in a linked list. I like to think of it as a turbo charged linked list. I guess you could make a defense for saying that a linked list is a basic form of this pattern.

So lets take a look at how this can be accomplished in C++…

#include <iostream>
using namespace std;

// Abstract class called Handler
// It is abstract because it has a pure virtual function.
// This prevents instances of Handler being created directly.
class Handler {
	protected:
		Handler *next;
	public:
		// Constructor
		Handler() { next = NULL; }

		// Pure virtual function
		virtual void request(int value) = 0;

		// Sets next handler in the chain
		void setNextHandler(Handler *nextInLine) {
			next = nextInLine;
		}
};


// SpecialHandler is a type of Handler but has a limit and ID
// It also determines if it can handle the request or needs to send it on
// If it is the last in the chain and can't handle it, it lets the user know.
class specialHandler : public Handler {
	private:
		int limit;
		int ID;
	public:
		specialHandler(int theLimit, int theID) {
				limit = theLimit; 
				ID = theID;
		}
		// Handles incoming request
		void request(int value) {
			if (value < limit) {
				cout << "Handler " << ID << " handled the request with a limit of " << limit << endl;
			}
			else if (next != NULL) {
				// Passes it on to the next in the chain
				next->request(value);
			}
			else { 
				// Last in chain, so let the user know it was unhandled.
				cout << "Sorry, I am the last handler (" << ID << ") and I couldn't even handle that request." << endl; 
			}
		}
};


int main ()
{

	// Create three special handlers with ids "1, 2 and 3"
	// Since a specialHandler is a type of "Handler" they are legal statements.
	Handler *h1 = new specialHandler(10, 1);
	Handler *h2 = new specialHandler(20, 2);
	Handler *h3 = new specialHandler(30, 3);

	// Chain up the handlers together
	h1->setNextHandler(h2);
	h2->setNextHandler(h3);

	// Handled by handler 2 because handler 1 couldn't handle it,
	// so it passed it on to handler 2 which could handle since it is less than 20
	h1->request(18);

	// No handler could handle this, so will trigger last handler's else
	// statement showing that it is the last and still couldn't handle the request.
	// You could also tack on a default version for the end if you like.
	h1->request(40);

	// Clean up our pointers
	delete h1;
	delete h2;
	delete h3;
	
	return 0;
}

The in-code comments say a lot about what is going on. But as a recap we are creating an abstract class (that is a class you can’t instantiate yourself but you can inherit from) and creating specialHandler objects through inheritance. We use these specialhandler objects to chain them to one another through the setNextHandler function. We also implement a request function which is going to take in a request, evaluate it and determine whether or not the class can handle it or pass it to the next handler in the chain.

So for our example functionality inside of main() we give the value “18” to the first handler. That handler will look at the value and compare it against “limit” which has been set to “10”. Since 18 is larger than 10, it is going to pass it on to the next handler. The second handler is going to take the 18 and compare it to “20” and determine if it can handle it. In this instance it can so it prints out a message saying that it can handle it.

Our second test is going to pass 40 to the first handler. It is larger than 10 so it passes it onto the second handler. It is larger than 20 so it passes it onto the third handler. Again it is larger than 30 but since the third handler is the last in the chain, it decides to print the contents of the “else” and prints that it still could not handle the value.

In real world examples each handler here in the chain might be various types of objects all inherited from “Handler”. One might be specialHandler, one might be superHandler, and another might be “iHandleEverythingHandler”. Each handler will have its own criteria for evaluating the value and one might be created just so it can be the “default case” at the end of the chain.

Taking this to the extreme, each class in this chain could be a completely separate subsystem where if a request comes in it will be routed to the correct computer to handle the request. You might see it in load balancing across network programs or handling calls in a call center. The possibilities are endless.

Analyze the example, tinker with it and see if you can create another class inherited from Handler. See if you can add it in the middle of the chain. For practice make the class handle values 23 to 26 only and place it in the proper place in the chain.

Hope you have fun with this little project and see the value in this pattern. And if that supervisor ever shows up again, pass the buck to that guy across the hall you hate and make him the last one in the chain! Thanks for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 20 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.