This episode covers a pattern that is not as well known as some of the recent ones.  This time we look at the chain of responsibility pattern.  This is also our first foray into the behavioral patterns.  These may be techniques you have used without knowing they had a formal name or related pattern.

The Chain of Responsibility Pattern Defined

As always, we will start with the “Gang of Four” intent to set the stage for our discussion.

“Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.  Chain the receiving objects and pass the request along the chain until an object handles it.”

This intent is a lengthy one.  The key is in the second sentence.  We are going to send a request and objects either respond or pass it along the chain.  This is a highly common pattern in graphical controls and the related event processing.  We also see this in other areas like a try-catch block in some instances.  Generally, there is a hierarchy or priority we implement in the chain or move from a specific to a general case in determining the response.

Applying The Pattern

The implementation is an interface that provides a way to make a call on an object from an external source.  That interface method will often provide a return value that indicates whether there was processing performed.  That is not a requirement though.  There will also be some way to progress through the collection (or layers) of classes that form the chain.

Java, PHP, C#, etc.

Once again, a chain of responsibility is an interface.  There might be a case where a class and inheritance would work, but that often is too tightly coupled.  Remember that the intent is to avoid coupling.  Thus, the looser the relationships, the better.  Therefore, the implementation is roughly the same across object-oriented languages.  They all support interfaces and nothing special is needed whether you use C#, Java, PHP, or something else.

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a lifetime learner as a developer, designer, and manager of software solutions. Rob is the founder of RB Consulting and has managed to author a book about his family experiences and a few about becoming a better developer. In his free time, he stays busy raising five children (although they have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax or working on his ballroom dance skills.

Leave a Reply