Chain of Responsibility Design Pattern in Java

The Chain of Responsibility design Pattern is one of the Behavioural design patterns of JAVA. As the name suggests, this pattern creates a chain of elements that pass on responsibility when called for in code. This design pattern is mainly used to reduce coupling in a code.

Definition

By definition, the Chain of Responsibility design pattern creates a chain of receiver objects. When a client request interacts with the program, the request is countered by these objects. The chain moves forward when one object is not able to serve it. Each object in the chain contains a reference to the next object in the chain. Coupling between objects is reduced significantly as an object only needs to know its link in front and back of the chain. Other properties of the chain can work independently.

Example and Code

A common example of this design pattern is the JAVA Servlet Filter. When a HTTP request is sent, several filters try to process the request.

public class ServeletFilter implements Filter {     //JAVA has a defined filter class that is extended here
public void process( ServletRequest req, ServeletResponse res, FilterChain chain)
chain.process(req, res);
}
}

/* This is a general class. Inside this class any request can be formulated and processed along the responsibility chain*/

When to use the Chain of Responsibility design Pattern

There are four situations where this pattern is used.

  • This pattern is preferred when a program is required to decouple the sender and receiver of a request.
  • When there are several objects in your code that have the resources of handling a particular request.
  • If a request is not object specific, the chain of responsibility will determine which object will ultimately process the request.
  • If a handler is not specified explicitly in the request, this pattern comes in handy.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.