Chain of Responsibility Design Pattern in Java is one of the articles among the collection of articles dedicated to explaining OOP Design Patterns in Java.
In 1994, four authors, Addison-Wesley, by Erich Gamma, Richard Helm, Ralph Johnson, John Vissides wrote a book: Design Patterns: Elements of Reusable Object-Oriented Software. There they have included 23 object-oriented design patterns and Chain of responsibility design pattern is one of them. The Chain of Responsibility design pattern is categorized as a Behavioural Pattern since it is used to control the behaviour of the application.
What is Chain of Responsibility Design Pattern?
Chain of Responsibility design pattern passes the requests along a chain of potential handlers until it reaches the end of the chain. A single request can be handled by one or more handlers while it travels through the chain or it can reach the end without handling either of them.
When to use Chain of Responsibility Design Pattern?
When client don’t know which handler or handlers are responsible to handle the request. So the client only need to create the chain and pass the request to it. Then the chain itself take the responsibility of forwarding the request along the chain. If there are handlers who can handle it, they will handle it as forward to the next handler in the chain until it reach the end of the chain.
Examples of The Responsibility Design Pattern in Java
Java Example Program
Let’s create a simple Java program to understand CoR design pattern.
There are lots of real-world scenarios in which we can use the CoR design pattern. For this example, I will choose a simple scenario where we need to validate the input request but the validators can be selected only at the runtime.
Now we need to create Handler interface. It has two methods. One is to validate the Person and the other one is to set the next handler.
Now we can create handler for each of the parameters that we need to validate.
Now in the Main method, let’s define the chain. After declaring the chain, we can send the object to be processed to the first node of the chain. We have already defined the chain so the chain itself does the processing and exit at the end. Here we are printing the results after it. In this case ValidateMessages list.
Chain of Responsibility design pattern passes the requests along a chain of potential handlers until it reaches the end of the chain. This pattern mainly used when the client do not know which handler or handlers are responsible to process the request. This decouple the client with it’s handlers. But we need to be more careful when creating the chain as we can miss some handlers or we may fail to properly organise the order of handlers in the train.
Please find the source code on Github.