Core Java

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.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mail4blogs
Mail4blogs
11 years ago

Thanks for sharing

Ali
10 years ago

Awesome.

Back to top button