The Chain of Responsibility Pattern in Java

Introduction to the Chain of Responsibility Pattern

Design pattern in a simple meaning, is a way to design reusable object-oriented code. We can think of ways to design our classes, interfaces, enums and their members so that the code is reusable but flexible.

There are 23 most important design patterns, pioneered by the book Design Patterns: Elements of Reusable Object-Oriented Software, written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides or Gang of Four for short. We will cover these design pattern one by one.

The Chain of responsibility pattern is used to achieve loose coupling where a request from a client is passed to a chain of objects to process them. Then the objects in the chain will decide which to process the request and if the request is required to be sent to the next object in the chain or not.

Implementation of Chain of Responsibility Pattern in Java

Say we will iterate from 1 to 10 and each time we need to output a line “This number is an odd number” or “This number is an even number”. Clearly this is very simple, but we can use this to demonstrate how The Chain of responsibility pattern works.

First we create the Chain interface in Chain.java (in src folder):

public interface Chain {
  void setNext(Chain nextChain);
  void execute(int request);
}

With the setNext() method we can set the order of chaining dynamically.

Then, we create two concrete chains, the first is the EvenChain.java:

public class EvenChain implements Chain{
  private Chain nextChain;
  public void setNext(Chain nextChain) {
    this.nextChain = nextChain;
  }
  public void execute(int request) {
    if (request % 2 == 0)
      System.out.println(request
          + " : This number is an even number");
    else nextChain.execute(request);
  }
}

And the OddChain.java

public class OddChain implements Chain{
  private Chain nextChain;
  public void setNext(Chain nextChain) {
    this.nextChain = nextChain;
  }
  public void execute(int request) {
    if (request % 2 != 0)
      System.out.println(request
          + " : This number is an odd number");
    else nextChain.execute(request);
  }
}

And in Test.java

import java.util.stream.IntStream;
public class Test {
  public static void main(String[] args){
    //create two chains
    Chain even = new EvenChain();
    Chain odd = new OddChain();
    //add odd chain to even chain
    even.setNext(odd);
    //send 10 request to the chains
    IntStream.rangeClosed(1, 10)
        .forEach(even::execute);
  }
}

And we have the output:

1 : This number is an odd number
2 : This number is an even number
3 : This number is an odd number
4 : This number is an even number
5 : This number is an odd number
6 : This number is an even number
7 : This number is an odd number
8 : This number is an even number
9 : This number is an odd number
10 : This number is an even number

Leave a Reply