Behavioral Patterns  «Prev  Next»

Chain of Responsibility

The Chain of Responsibility pattern establishes a chain within a system, so that a message can either be handled at the level where it is first received, or be directed to an object that can handle it.

Chain of Responsibility consisting of abstact base class and two ConcreteHandler classes
Chain of Responsibility Java Code


The following lists the benefits of using the Chain of Responsibility pattern:
  1. Reduced coupling
  2. Added flexibility in assigning responsibilites to objects
  3. Allows a set of classes to behave as a whole, because events produced in one class can be sent on to other handler classes within the composite.

When To Use:

You should use the Chain of Responsibility Pattern when:
  1. More than one object can handle a request, and the handler is not known.
  2. You want to issue a request to one of several objects without specifying the receiver completely.
  3. The set of objects that can handle a request should be specified dynamically.
In Object Oriented Design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain. In a variation of the standard chain-of-responsibility model, some handlers may act as dispatchers, capable of sending commands out in a variety of directions, forming a tree of responsibility. In some cases, this can occur recursively, with processing objects calling higher-up processing objects with commands that attempt to solve some smaller part of the problem; in this case recursion continues until the command is processed, or the entire tree has been explored. An XML interpreter might work in this manner.
This pattern promotes the idea of loose coupling, which is considered a programming best practice.

Chain of Responsibility Pattern consisting of 1)Client, 2) Handler, 3) ConcreteHandler