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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Coding
  3. Languages
  4. Simple Example to Illustrate Chain Of Responsibility Design Pattern

Simple Example to Illustrate Chain Of Responsibility Design Pattern

Mohamed Sanaulla user avatar by
Mohamed Sanaulla
CORE ·
Oct. 03, 12 · Interview
Like (2)
Save
Tweet
Share
18.43K Views

Join the DZone community and get the full member experience.

Join For Free

GoF Design pattern book states the intent of Chain of Responsibility pattern as:

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

 

 

 

 

 

 

 

 

 

 

 

 

Requests Parser (programming language) Object (computer science) Design

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Data Leakage Nightmare in AI
  • Java Development Trends 2023
  • Using JSON Web Encryption (JWE)
  • The 31 Flavors of Data Lineage and Why Vanilla Doesn’t Cut It

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: