DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Using the Chain of Responsibility Design Pattern in Java
  • Reactive Programming in Java: Using the WebClient Class
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • Node.js Walkthrough: Build a Simple Event-Driven Application With Kafka
  • You Can Shape Trend Reports: Participate in DZone Research Surveys + Enter the Prize Drawings!
  • Theme-Based Front-End Architecture Leveraging Tailwind CSS for White-Label Systems
  • Build an Advanced RAG App: Query Rewriting
  1. DZone
  2. Coding
  3. Languages
  4. Chain of Responsibility Pattern Tutorial with Java Examples

Chain of Responsibility Pattern Tutorial with Java Examples

Learn the Chain of Responsibility Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
Mar. 30, 10 · Tutorial
Like (4)
Save
Tweet
Share
160.4K Views

Join the DZone community and get the full member experience.

Join For Free

Today's pattern is the Chain of Responsibility, a simple way to decouple the handling of requests.

Chain of Responsibility in the Real World 

The idea of the Chain Of Responsibility is that it avoids coupling the sender of the request to the receiver, giving more than one object the opportunity to handle the request.  This process of delegation appears quite frequently in the real world where there is one interface for the customer to go through. One example could be a bank, where an application that you send in to the bank branch may be handled by one particular department. Another example is a vending machine, where you can put in any coin, but the coin is passed on to the appropriate receptacle to determine the amount that the coin is worth. 

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Chain of Responsibility Pattern

The Chain of Responsibility is known as a behavioural pattern,as it's used to manage algorithms, relationships and responsibilities between objects. Thedefinition of Chain of Responsibility provided in the original Gang of Four book on DesignPatterns states: 

Gives more than one object an opportunity to handle a request by linking receiving objects together.  

Chain of Responsibility allows a number of classes to attempt to handle a request, independently of any other object along the chain. Once the request is handled, it completes it's journey through the chain.

Let's take a look at the diagram definition before we go into more detail.

Image title


 The Handler defines the interface required to handle request, while the ConcreteHandlers handle requests that they are responsible for.  If the ConcreteHandler cannot handle the request, it passes the request onto it's successor, which it maintains a link to. 

The objects in the chain just need to know how to forward the request to other objects.  This decoupling is a huge advantage, as you can change the chain at runtime. 

Would I Use This Pattern?

This pattern is recommended when either of the following scenarios occur in your application:

  • Multiple objects can handle a request and the handler doesn't have to be a specific object
  • A set of objects should be able to handle a request with the handler determined at runtime
  • A request not being handled is an acceptable outcome.

The pattern is used in windows systems to handle events generated from the keyboard or mouse. Exception handling systems also implement this pattern, with the runtime checking if a handler is provided for the exception through the call stack. If no handler is defined, the exception will cause a crash in the program, as it is unhandled.

In JavaEE, the concept of Servlet filters implement the Chain of Responsibility pattern, and may also the request to add extra information before the request is handled by a servlet.

 

So How Does It Work In Java?

Now let's take a look at how we might implement the Chain of Responsibility with a code example. Let's use an email client as an example. You might set up some rules to move a message into a particular folder depending on who it's from. First we'll need to create our EmailHandler interface.

//Handlerpublic interface EmailHandler{//reference to the next handler in the chainpublic void setNext(EmailHandler handler);//handle requestpublic void handleRequest(Email email);}

 

Now let's set up two concrete handlers, one for business mail and one for email originating from Gmail. These handlers pass on the request if it doesn't interest them 

public class BusinessMailHandler implements EmailHandler{private EmailHandler next;public void setNext(EmailHandler handler){    next = handler;}public void handleRequest(Email email)    {if(!email.getFrom().endsWith("@businessaddress.com"){    next.handleRequest(email);}else{    //handle request (move to correct folder)}}}
public class GMailHandler implements EmailHandler{private EmailHandler next;public void setNext(EmailHandler handler){    next = handler;}public void handleRequest(Email email)    {if(!email.getFrom().endsWith("@gmail.com"){    next.handleRequest(email);}else{    //handle request (move to correct folder)}}}

Now let's set up a client that manages the handlers - this will actually be our EmailProcessor. 

public class EmailProcessor{//maintain a reference to the previous handler so we can add the next oneprivate EmailHandler prevHandler;public void addHandler(EmailHandler handler){if(prevHandler != null){prevHandler.setNext(handler);}prevHandler = handler;}}

This class allows us to add in new handlers at any stage. Finally, the email client itself uses the EmailProcessor to look after all incoming messages 

 

//email client public class EmailClient{private EmailProcessor processor; public EmailClient(){   createProcessor();}private void createProcessor(){processor = new EmailProcessor();processor.addHandler(new BusinessMailHandler());processor.addHandler(new PersonalMailHandler());}public void addRule(EmailHandler handler){   processor.addHandler(handler);}public void emailReceived(Email email){processor.handleRequest(email);}public static void main(String[] args){EmailClient client = new EmailClient();}}

If new rules, for forwarding email to particular folders are added, we can add the handler to our email processor at runtime using the addRule() method in the client.

Watch Out for the Downsides

As with the pattern, Chain of Responsibility can make it difficult to follow through the logic of a particular path in the code at runtime. It's also important to note that there is the potential that the request could reach the end of the chain and not be handled at all.

Next Up

We're going to look at the Command pattern later this week.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern


Requests Object (computer science) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Using the Chain of Responsibility Design Pattern in Java
  • Reactive Programming in Java: Using the WebClient Class
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: