Should you make your C++ classes more intelligent or centralize the intelligence and use dumbed-down surrounding classes? The natural world tends to prefer a pass-the-parcel style of distributed intelligence, which reduces single points of failure and potentially leads to more stable systems. In this article, Stephen Morris shows you how to raise the IQ of your classes while simultaneously allowing other (possibly) more-qualified classes to handle specific problems. The chain of responsibility pattern provides an elegant model for facilitating this behavior.

Like this article? We recommend

The networking problem hasn’t been solved yet—not even nearly!
Networks are populated with users who are increasingly hungry for bandwidth and
computational resources. I should know—I’m one of them! Just the
other day, I downloaded about 200MB of software in an hour of usage on a Wi-Fi
network. So, that’s a total of roughly 200 * 8 * 1024 * 1024 bits in 3600
seconds, or a bandwidth requirement of 0.466Mbps. This download rate was
probably limited more by the Web sites concerned than the local network, which
boasted a link speed of 11Mbps.

Not surprisingly, networks are busy these days! With high levels of traffic
and bursty usage patterns, networks often emit warning messages to management
software. Large national networks typically emit gigabytes of such messages on a
daily basis. Should the management software provide one big handler for all such
messages, or is it better to allow messages to intelligently seek out an
appropriate handler? Both approaches have their merits, al though the former is
more common. The chain of responsibility pattern provides a model for the
latter.

The Takeaway

This article shows you some important (and hopefully interesting!) aspects of
modern network operations. In this context, you’ll also see how to define
classes that use the chain of responsibility pattern. A sneak preview of the
finished code is illustrated in Listing 1, in which three related entities make
up the chain of responsibility.

Listing 1 Implementation of the Chain of Responsibility

The last line in Listing 1 simulates a message being sent to the lowest level
in the chain (more on this later). As usual, if you like you can download the
full program source (one C++ file and one header file), build it and try it out
for yourself. Let’s now get the background information out of the way!