Chain Responsiblity Design Pattern – Java

The Concept of this Design Pattern is decoupling the sender and receiver.

Each receiver doesn’t know about it’s sender but contains the next receiver(successor to it) and so forth .

Example of a basic Java Logger with a chain of responsibilty:

import java.util.logging.Logger;

Logger logger = Logger.getLogger(SomeLogger.class.getName());

logger.setLevel(Level.Severe);

ConsoleHandler handler = new ConsoleHandler();

handler.setLevel(Level.Severe);

logger.addHandler(handler);

logger.Info("Won't be seen");

logger.Severe("will be seen");

 

Another more elaborated example:

Define an interface for a handler:

package com.yairshinar.chainofresponsibility;

public interface ResponsibiltyChainItem {

  void setNextChain(ResponsibiltyChainItem nextChain);

  void execute(SomeClass someClassInstance);

}

Next implement some concrete chain items:

public class ExampleChain implements ResponsibiltyChainItem {

 private ResponsibiltyChainItem chain; 
@Override public void setNextChain(ResponsibiltyChainItem nextChain) {      
  this.chain=nextChain; 
} 
@Override public void execute(SomeClass someClassInstance) {   
  if(someClassInstance.someMethod() >= 100){
    System.out.println("Approved");
  }
  else  { this.chain.execute(someClassInstance); } 
}


public class ExampleChainAgain implements ResponsibiltyChainItem {

private ResponsibiltyChainItem chain; 

@Override public void setNextChain(ResponsibiltyChainItem nextChain) { 
  this.chain=nextChain; 
} 
@Override public void execute(SomeClass someClassInstance) { 
  System.out.println("Approved");
}

And, last utilize them in the program:

 

public static void main(String[] args) {
  ExampleChain example = new ExampleChain();
  ExampleChainAgain exampleNext = new ExampleChainAgain(); 
  example.setNextChain(exampleNext);
  System.out.println("Enter a number: ");
  Scanner input = new Scanner(System.in);
  example.execute(new SomeClass(input.nextInt()));
}