Other Tutorials

Chain Of Responsibility Design Pattern In Java

Introduction:

In this tutorial, we’ll learn how to implement the Chain Of Responsibility Pattern in Java.

The Chain Of Responsibility design pattern involves having a chain of objects that are together responsible for handling a request. When a client sends a request, the first handler will try to process it. If it can process it, then the request processing ends here. However, if the handler cannot handle the user request, it will then go to the next handler in the chain. This process will continue until either one of the handlers in the chain successfully processes the request or the chain ends. If the entire chain is not able to handle the request, it means that the request remains unsatisfied.

Why Use Chain Of Responsibility?

The Chain Of Responsibility is a pretty important design pattern in our software industry. It offers several benefits:

  • It promotes loose coupling between the user and the system as the user doesn’t need to care about which object will process its request
  • Java exception handling mechanism also makes use of this pattern. If no suitable catch block is found, the request is delegated to the caller method to handle until we find an appropriate handler
  • This pattern also finds its applications in filtering user requests by letting the request pass through a chain of filters

UML Representation:

The UML representation of the Chain Of Responsibility pattern looks similar to:

Chain Of Responsibility Design Pattern

Here, we have the following types of objects:

  • Client: the code making user requests
  • Handler: an abstract superclass or an interface defining the request handler method
  • ConcreteHandler: the implementation classes for the Handler

The handler objects are connected from one to the next in the chain. Also, each concrete handler handles the request in its own unique way.

Defining the Abstract Handler:

Let’s implement a request filtering logic using the Chain Of Responsibility.

Firstly, we’ll define an abstract RequestFilter class:

Defining the Concrete Handlers:

Now, let’s define the very first filter class in the chain, which will block request from suspicious IP addresses:

Similarly, let’s define the second filter of our chain, which will block unauthorized requests:

And the very last filter which will identify and block users with exceeded login attempts:

Invoking the Chain:

Finally, it’s time to knit them together in a chain:

Here, each user request will follow the below chain of filtration:Filter Chain

As soon as one of these filter criteria gets matched, the matched filter will filter out that user request. This also means that the remaining chain will be skipped.

Conclusion:

In this tutorial, we learned how and when to use the Chain Of Responsibility design pattern.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *