Pattern: Chain of Responsibility

Synopsis

The purpose of this pattern is to avoid coupling the sender of a request to its receiver by giving more than on object an opportunity to handle the request.

Context

The Chain of Responsibility pattern addresses the problem of having more than one object that is capable of handling a request.  It also provides a way to avoid coupling the sender and the receiver of a request, which leads to increased flexibility.  Handlers can be added to or removed from a client without significant changes to the client.

Forces

If there are multiple objects that can handle a request or if coupling the sender and receiver of a request is undesirable, consider using the Chain of Responsibility.

Solution

Chain the receiver objects in a linked list and pass the request along the chain until an object handles it.

 

(UML diagram from http://www.developer.com/java/other/article.php/631261)

Consequences

Implementation

Example Code

Related Patterns

Chain of Responsibility is often applied in conjunction with Composite, where a Component’s parent acts as its successor to allow backwards traversal up a tree hierarchy.


References

The Object-Oriented PatternDigest, Chain of Responsibility: http://patterndigest.com/patterns/ChainOfResponsibili.html

Follow the Chain of Responsibility:
http://www.javaworld.com/javaworld/jw-08-2003/jw-0829-designpatterns.html