Java Tech Updates

Java Tech Updates

  • Blog
  • Code
  • NEWS
  • About Us
  • Contact us
  • Privacy
  • Write for us
Home  /  Code  /  Tutorial Alert: Chain of Responsibility Pattern With JAVA

Tutorial Alert: Chain of Responsibility Pattern With JAVA

Vijay September 16, 2016 Code 1 Comment
Java

In java outsourcing company, developers design their code efficiently to make it more reliable with the help of design methodologies. In this article, you will learn about the chain of responsibility pattern used by professionals to make the code more reliable.

Introduction

In Java, to make the code more reliable we should, design our code efficiently that can be done by applying design methodologies such as OOPs, OOAD, design principles and patterns into applications.

Chain of Responsibility pattern is a behavioral design pattern which truly makes the code loose coupling. It decouples sender of the request to the receiver, where chain of objects are there to process the request and the request use to starts or process with the first object in the chain, it proceeds if that object the solution otherwise the request is forwarded to the next object in the chain in order to handle or process that request. This chaining will happen until finding the solution object in the chain.

GOF states that – “Gives larger than one object an opportunity to handle a request by linking receiving objects together.”

handlerHandler – interface to handle the requests

Concrete Handler – A request handler which handles the request that they are responsible for otherwise it sends the request to its successor.

Client – send the request to the handler to process the request. The first handler object in the chain would invoke by the client.

For e.g.

java.util.logging.Logger, javax.servlet.Filter are the examples that are followed by a chain of responsibility design pattern.

Let us take an example of Gmail, where we could see the emails categorized like Primary, Social and Promotion.

Social – Emails from Facebook, Twitter, Google plus are in the social category.
Promotion – Emails from Paytm, Flipkart, Amazon offers are in the promotion category.
Primary – Other emails from people and friends are company are in the primary category.

We can also have our folder or category or rule for the basis of the incoming email on the subject, from, to and all.

So, how could we do this in code with good design?

// Handler interface

public interface GmailHandler { 

   public void setNext(GmailHandler gmailHandler); //to set next handler 

   public void handleRequest(Email email); //to handle or process the emails

}
// Request object

public class Email {   

   private boolean is Social;

   private boolean is Promotion;

   private boolean is Primary;

   private Boolean is Spam;

  

   public boolean is Social() {

         return is Social;  // returns true when emails from facebook, twiiter, google plus

    }

  public boolean is Promotion() {

         return is Promotion; // returns true when emails from paytm, flipkart, amazon offers     

    }

  public boolean is Primary () {

        return is Primary; // returns true when emails not from social and shopping sites      

    }

   public boolean is Spam() {

         return is Spam;      

    }

   // more members and methods on content of email and other details

}
// Concrete Handler or Request Handler

public interface SocialEmaiHandler {

 

   private GmailHandler handler;
public void setNext(GmailHandler handler) {

        this.handler = handler;

   }

   public void handleRequest(Email email) {

         if(email.isSocial()) {

                    // proceeds or handles social email contents, keeps in social category

          } else {

                   handler.handleRequest(); // proceeding with next handler in the chain

          }

   }

}
// Concrete Handler or Request Handler

public interface PromotionEmailHandler { 

   private GmailHandler handler; 

   public void setNext(GmailHandler handler) {

        this.handler = handler;

   }

  public void handleRequest(Email email) {

         if(email.isPromotion()) {

                    // proceeds or handles promotion email contents, keeps in promotion category

          } else {

                   handler.handleRequest(); // proceeding with next handler in the chain

          }

   }

}
// Concrete Handler or Request Handler

public interface PrimaryEmailHandler {

   private GmailHandler handler;

   public void setNext(GmailHandler handler) {

        this.handler = handler;

   }

   public void handleRequest(Email email) {

         if(email.isPrimary()) {

                    // proceeds or handles primary email contents, keeps in primary category

          } else {

                   handler.handleRequest(); // proceeding with next handler in the chain

          }

   }

}
// Client

public class EmailClient {

  private GmailHandler handler;

  public EmailClient() {

        createProcessChain();

  }

  public void addRule(GmailHandler handler){

       if(this.handler == null)

             this.handler = handler;

       else

                this.handler.setNext(handler);

  }

  public void sendRequest(Email email){

       this.handler.handleRequest(email);

  }

  public void createProcessChain() {

       addRule(new SocialEmailHandler());

       addRule(new PromotionEmailHandler());

       addRule(new PrimaryEmailHandler());      

  }

  public static void main(String[] aa){

      EmailClient client = new EmailClient();

      Email email = new Email();

      email.setIsPromotion(true);

      client.sendRequest(email);

      Email email = new Email();

      email.setIsPrimary(true);

      client.sendRequest(email);

      Email email = new Email();

      email.setIsSocial(true);

      client.sendRequest(email);

  }

}

 Conclusion:

Just think that, if we didn’t follow this chain of responsibility design pattern how would we achieve this solution? We would write if and else if the block on each case or category!!?? If we do so, it creates n-path complexity problem to our code, and it is very difficult to change the code to adopt a new feature i.e each time we have to rework with the implementation.

So, Chain of responsibility pattern helps us to makes the code loose coupling and easy to adopt a new feature i.e. if we want to add a new rule or category like spam to email simply we can add a new concrete handler called SpamEmailHandler that implements Handler interface and most importantly we are adding feature to our code without touching the existing implementation.

As you now know that chain of responsibility is a behavioral design pattern used by Java outsourcing company professionals to design the code. Any point you did not get can be asked in comments.

Tags: Chain of Responsibility Pattern, Java, Java outsourcing company
Previous Article
Next Article

About Author

Vijay

Related Posts

  • spring cloud stream in Java

    Use of Spring Cloud Stream in Java

    March 16, 2017
  • Java development copmany

    Spring Retry framework for Better Java Development

    January 19, 2017
  • spring-factory-beans

    How to Use Spring Factory Beans in Java Development

    January 4, 2017

1 Comment

  1. Pingback: How To Use Jenkins Web Based Build Management Tool In Java Applications? - Java Tech Updates

Leave a Reply

Cancel reply

May i Help You !

Your Name (required)

Your Email (required)

Subject

Your Message

Popular Posts of The Month

  • Java developers Team
    Essential APIs access could be critical with Java 9 October 22, 2015
  • How To Use Jenkins Web Based Build Management Tool In Java Applications? July 22, 2016
  • Programmers And Developers Need To Wait More For Java 9 December 10, 2015
  • Java development with JRebel & XRebel
    JAVA DEVELOPMENT introducing the two diodes in this language November 19, 2015
  • Java 9 releases by JPI
    New access program for supporting Java 9 releases by JPI November 25, 2015
  • Attractive features in Java SE 8u 40
    Attractive features in Java SE 8u 40 November 9, 2015
  • Java Application Development Composure Of Miniprograms February 9, 2016
  • Java Programmers And The Joy Of Application Development May 11, 2016
  • spring-factory-beans
    How to Use Spring Factory Beans in Java Development January 4, 2017
  • cross-culture-business-communication
    The Why and How of Cross-Cultural Business Communication November 8, 2016
  • Java
    Tutorial Alert: Chain of Responsibility Pattern With JAVA September 16, 2016
  • cloud computing in web development
    Importance of Cloud Computing in Web Development Sector September 8, 2016
  • IOT and Java
    Is Java the Missing Link Between IoT and Future Application? February 1, 2017
  • Java development copmany
    Spring Retry framework for Better Java Development January 19, 2017
  • scala-development-by-javaprofessionals.net
    Scala Development Vs Java- A Never Ending Debate January 1, 2016
  • Java Outsourcing
    Spring Data Rest – Repositories August 23, 2016
  • Java Software Development
    JPI To Offer Rapid Deployment Package To Java Development Teams December 21, 2015
  • java application development
    Java App Development Using Hibernate December 10, 2015
  • Java developers Team
    MyEclipse 2015 Updates for Java Developers December 7, 2015
  • cache management in java
    Cache Management in Java – Caching Techniques June 11, 2016

Recent Posts

  • Employee Performance
    Mobile & PC Screen Recorder to Measure Employee Performance March 18, 2019
  • Social Media Strategy
    Why Animated Video is a Best Strategy for Your Social Media March 4, 2019
  • Java anomaly detection tool
    Top 5 Java Anomaly Detection Tools February 14, 2018
  • Java development
    2017, stayed a big year of Twists in Java Development, Must Watch! February 9, 2018

What Others Are Reading

  • java web development
    10 MICRO METRICS FOR YOUR PERFORMANCE REPORTS September 12, 2017
  • Spring Boot – Working with Multiple Database July 12, 2016
  • Java anomaly detection tool
    Top 5 Java Anomaly Detection Tools February 14, 2018
  • Java 9 releases by JPI
    New access program for supporting Java 9 releases by JPI November 25, 2015

Random Posts

  • WHAT, WHY, HOW Inheritance in Java December 16, 2015
  • spring-factory-beans
    How to Use Spring Factory Beans in Java Development January 4, 2017
  • Web Development
    Semalt Explains What SEO Aspects You Should Mind In Web Development July 28, 2017
  • Java developers Team
    MyEclipse 2015 Updates for Java Developers December 7, 2015

Popular Posts

  • Java developers Team
    Essential APIs access could be critical with Java 9 October 22, 2015
  • How To Use Jenkins Web Based Build Management Tool In Java Applications? July 22, 2016
  • Java development with JRebel & XRebel
    JAVA DEVELOPMENT introducing the two diodes in this language November 19, 2015
  • Programmers And Developers Need To Wait More For Java 9 December 10, 2015
Theme by Dashing Themes | Proudly Powered by WordPress