Chain of Responsibility

You have a hierarchy of components, and they respond to events. One event comes in, but the element which receives it doesn’t know what to do with it. It can’t handle the event. In this instance, you push the event up to the parent and hope they can respond to the message.

At this point, you have created a Chain of Responsibility. A class overrides the handling of the message if it can, and the default implementation is to propagate further along the chain, usually upwards.

But what if an object along the path doesn’t handle the error and drops it without handing it to the next parent? I prefer the certainty of a method to call on objects that walk the chain for me. It demands all visited objects return a value stating whether they handled the message or not.

The pattern doesn’t seem OO specific, as interrupt handlers and chains for messages or events have been around for a long time in procedural code. The pattern is an example of how it could be implemented in OO code. For someone new to OO, this could be reason enough for its inclusion.

“Sorry, nothing to do with me. I’ll go ask my manager.”