From the course: Java Design Patterns: Behavioral Part 1

Understanding the Chain of Responsibility pattern - Java Tutorial

From the course: Java Design Patterns: Behavioral Part 1

Start my 1-month free trial

Understanding the Chain of Responsibility pattern

- [Instructor] If you have a situation where you have some code that needs to make a request, but you don't know until runtime which object will be handling that request, you might want to consider using the chain of responsibility pattern. As a real world example, imagine someone is using a software application and they find a bug, they need to tell someone about it so that the bug will get fixed. So they raise a support ticket in an online support system. And that gets picked up by a live support worker. In some cases, the life support worker might be able to respond directly to the user. If it's just a case of answering a question or something, but as this is a bug in the software, they then need to tell the product manager about the bug and pass on the details to them. The product manager looks at the impact of the bug and they decide they want to prioritize getting it fixed. So they ask a developer to fix it. That developer is working on something else they don't have time to fix it, but they do know another developer who does have time so they pass it on to them. That developer is able to fix the bug, so the other person who does it. In this situation the request to fix the bug is potted on this long chain, from the person who found it to the developer who fixed it. This is the concept of the chain of responsibility pattern. In Java Applications, the chain of responsibilities is used to pass along request to different objects until it finds the one that can handle it. The main benefits of this pattern is that it decouples the sender of the request from the receiver. Example of used cases for this in Java include, handling authentication where different types of authentication might be needed, separate filters for processing HTTP requests and things like buttons and used interfaces, where the action taken when it's clicked depends on the context. There are a few things to watch out for, when you're implementing the chain of responsibility button. If it's not implemented correctly, it candidates to circular chains by the requests, just keep getting passed round in a circle to the same objects. There's also a chance that the requests just never gets handled, and it can also be difficult to debug problems with this design. Change of responsibility can lead say a quite confusing stack traces, and they can be quite confusing to follow. But if you do have a number of objects that could handle a certain requests and you want the right ones to be chosen dynamically. Then the chain of responsibility pattern is well worth considering.

Contents