Subscribe to Martyr2's Programming Underground        RSS Feed

Chain of Responsibility Pattern - C++

Icon 2 Comments
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!

<Theme music from "The Office" with the sound of breaking dishes in the background>

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 {
		Handler *next;
		// 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 {
		int limit;
		int ID;
		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
			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

	// 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

	// 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.

	// 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! :)

If you want more blog entries like this, check out the official blog over on The Coders Lexicon. There you will find more code, more guides and more resources for programmers of all skill levels!

2 Comments On This Entry

Page 1 of 1


23 December 2008 - 12:47 AM
I believe I spotted a potentially confusing error.

The first sentence of the paragraph right below the code box...specifically the parenthetical part...


(that is a class you can instantiate yourself but you can inherit from)

Shouldn't that be...

(that is a class you can't instantiate for yourself but you can inherit from)


I hope that's right. I don't believe C++ would have different abstract rules (other than syntax) than Java.

Another thing. (this is more of a question) I noticed there's no abstract keyword in C++. So when you write an abstract class, does having a virtual member function make it so it actually is an abstract class? If not, then what does make it one?


23 December 2008 - 05:00 PM
Thanks for pointing out the error. You are exactly right. I meant can't instead of can.

As for the abstract class question, you not only have to have at least ONE virtual function but that virtual function must also be "pure". Meaning that it will have to be overridden and thus you have to inherit from it to do that. A pure virtual function is using the keyword "virtual" but also adding = 0.

Since this pure virtual function must be overridden it has to be inherited from and can't create an actual instance of this object. Creating an actual instance would then allow you to access this virtual function which has no definition on its own, so that is illegal.

Virtual says that it CAN BE overridden and the pure part says that not only can it be overridden, it MUST BE (unless you want the child class to also be abstract).

Thanks for the comment and pointing out the clarification. :)
Page 1 of 1

October 2020

18192021 22 2324

Recent Entries

Recent Comments

Search My Blog

1 user(s) viewing

1 Guests
0 member(s)
0 anonymous member(s)