Home » Chain of Responsibility Pattern

Chain of Responsibility Pattern

by Online Tutorials Library

Chain Of Responsibility Pattern

In chain of responsibility, sender sends a request to a chain of objects. The request can be handled by any object in the chain.

A Chain of Responsibility Pattern says that just “avoid coupling the sender of a request to its receiver by giving multiple objects a chance to handle the request”. For example, an ATM uses the Chain of Responsibility design pattern in money giving process.

In other words, we can say that normally each receiver contains reference of another receiver. If one object cannot handle the request then it passes the same to the next receiver and so on.


Advantage of Chain of Responsibility Pattern

  • It reduces the coupling.
  • It adds flexibility while assigning the responsibilities to objects.
  • It allows a set of classes to act as one; events produced in one class can be sent to other handler classes with the help of composition.

Usage of Chain of Responsibility Pattern:

It is used:

  • When more than one object can handle a request and the handler is unknown.
  • When the group of objects that can handle the request must be specified in dynamic way.

Example of Chain of Responsibility Pattern

Let’s understand the example of Chain of Responsibility Pattern by the above UML diagram.

UML for Chain of Responsibility Pattern:

Chain of Responsibility Pattern UML

Implementation of above UML:

Step 1

Create a Logger abstract class.

Step 2

Create a ConsoleBasedLogger class.

File: ConsoleBasedLogger.java

Step 3

Create a DebugBasedLogger class.

File: DebugBasedLogger.java

Step 4

Create a ErrorBasedLogger class.

File: ErrorBasedLogger.java

Step 5

Create a ChainOfResponsibilityClient class.

File: ChainofResponsibilityClient.java

Output

You may also like