Chain Of Responsibility Design Pattern Example

Avoid coupling the sender of a request to the receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

The main intention in Chain Of Responsibility is to decouple the origin of the request and the handling of the request such that the origin of the request need not worry who and how its request is being handled as long as it gets the expected outcome. By decoupling the origin of the request and the request handler we make sure that both can change easily and new request handlers can be added without the origin of the request i.e client being aware of the changes. In this pattern we create a chain of objects such that each object will have a reference to another object which we call it as successor and these objects are responsible for handling the request from the client. All the objects which are part of the chain are created from classes which confirm to a common interface there by the client only needs to be aware of the interface and not necessarily the types of its implementations. The client assigns the request to first object part of the chain and the chain is created in such a way that there would be atleast one object which can handle the request or the client would be made aware of the fact that its request couldn’t be handled.

With this brief introduction I would like to put forth a very simple example to illustrate this pattern. In this example we create a chain of file parsers such that depending on the format of the file being passed to the parser, the parser has to decide whether its going to parse the file or pass the request to its successor parser to take action. The parser we would chain are: Simple text file parser, JSON file parser, CSV file parser and XML file parser. The parsing logic in each of these parser doesn’t parse any file, instead it just prints out a message stating who is handing the request for which file. We then populate file names of different formats into a list and then iterate through them passing the file name to the first parser in the list.

Lets define the Parser class, first let me show the class diagram for Parser class:

The Java code for the same is:

public class Parser {
  
  private Parser successor;
  
  public void parse(String fileName){
    if ( getSuccessor() != null ){
      getSuccessor().parse(fileName);
    }
    else{
      System.out.println('Unable to find the correct parser for the file: '+fileName);
    }
  }
  
  protected boolean canHandleFile(String fileName, String format){
    return (fileName == null) || (fileName.endsWith(format));
        
  }

  Parser getSuccessor() {
    return successor;
  }

  void setSuccessor(Parser successor) {
    this.successor = successor;
  }
}

We would now create different handlers for parsing different file formats namely- Simple text file, JSON file, CSV file, XML file and these extend from the Parser class and override the parse method. I have kept the implementation of different parser simple and these methods evaluate if the file has the format they are looking for. If a particular handler is unable to process the request i.e. the file format is not what it is looking for then the parent method handles such requests. The handler method in the parent class just invokes the same method on the successor handler.

The simple text parser:

public class TextParser extends Parser{

  public TextParser(Parser successor){
    this.setSuccessor(successor);
  }
  
  @Override
  public void parse(String fileName) {
    if ( canHandleFile(fileName, '.txt')){
      System.out.println('A text parser is handling the file: '+fileName);
    }
    else{
      super.parse(fileName);
    }
    
  }

}

The JSON parser:

public class JsonParser extends Parser {

  public JsonParser(Parser successor){
    this.setSuccessor(successor);
  }
  
  @Override
  public void parse(String fileName) {
    if ( canHandleFile(fileName, '.json')){
      System.out.println('A JSON parser is handling the file: '+fileName);
    }
    else{
      super.parse(fileName);
    }

  }

}

The CSV parser:

public class CsvParser extends Parser {

  public CsvParser(Parser successor){
    this.setSuccessor(successor);
  }
  
  @Override
  public void parse(String fileName) {
    if ( canHandleFile(fileName, '.csv')){
      System.out.println('A CSV parser is handling the file: '+fileName);
    }
    else{
      super.parse(fileName);
    }
  }

}

The XML parser:

public class XmlParser extends Parser {
  
  @Override
  public void parse(String fileName) {
    if ( canHandleFile(fileName, '.xml')){
      System.out.println('A XML parser is handling the file: '+fileName);
    }
    else{
      super.parse(fileName);
    }
  }

}

Now that we have all the handlers setup, we need to create a chain of handlers. In this example the chain we create is: TextParser -> JsonParser -> CsvParser -> XmlParser. And if XmlParser is unable to handle the request then the Parser class throws out a message stating that the request was not handled. Lets see the code for the client class which creates a list of files names and then creates the chain which I just described.

import java.util.List;
import java.util.ArrayList;

public class ChainOfResponsibilityDemo {

  /**
   * @param args
   */
  public static void main(String[] args) {
    
    //List of file names to parse. 
    List<String> fileList = populateFiles();
    
    //No successor for this handler because this is the last in chain. 
    Parser xmlParser = new XmlParser();

    //XmlParser is the successor of CsvParser.
    Parser csvParser = new CsvParser(xmlParser);
    
    //CsvParser is the successor of JsonParser.
    Parser jsonParser = new JsonParser(csvParser);
    
    //JsonParser is the successor of TextParser.
    //TextParser is the start of the chain. 
    Parser textParser = new TextParser(jsonParser);
    
    //Pass the file name to the first handler in the chain.
    for ( String fileName : fileList){
      textParser.parse(fileName);
    }

  }
  
  private static List<String> populateFiles(){
    
    List<String> fileList = new ArrayList<>();
    fileList.add('someFile.txt');
    fileList.add('otherFile.json');
    fileList.add('xmlFile.xml');
    fileList.add('csvFile.csv');
    fileList.add('csvFile.doc');
    
    return fileList;
  }

}

In the file name list above I have intentionally added a file name for which there is no handler created. Running the above code gives us the output:

A text parser is handling the file: someFile.txt
A JSON parser is handling the file: otherFile.json
A XML parser is handling the file: xmlFile.xml
A CSV parser is handling the file: csvFile.csv
Unable to find the correct parser for the file: csvFile.doc

Happy coding and don’t forget to share!

Reference: Simple example to illustrate Chain Of Responsibility Design Pattern from our JCG partner Mohamed Sanaulla at the Experiences Unlimited blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

2 Responses to "Chain Of Responsibility Design Pattern Example"

  1. Mail4blogs says:

    Thanks for sharing

Leave a Reply


four − 2 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close