Chain of Responsibility pattern is a behavioral pattern that sends data (a request, a Command) to an concrete handler object and if that handler object can't use/handle it, it passes the data/request to other objects along the chain until an handler object handles it.

overview

The Handler defines the interface required to handle request, while the ConcreteHandlers handle requests that they are responsible for.

Think of Chain of Responsibility as Servlet Filters. In Chain of Responsibility, the Handler (or you may call it Chain) defines the interface required to handle a request (a Command), while each concrete handler object is supposed to handle the data/request that it is responsible for. Every node in the chain will have the responsibility to decide if they can serve the request/Command. If it can't, it'll then pass the data/request to the next concrete handler object in the chain. Once the request is handled, it completes it's journey through the chain. However, it is possible that no handler can handle the request.

The chain sequence of the handler objects are set up in the client code by linking up one handler to another via setNextChain() as seen in the sample code below.

chain of responsibility design pattern code example

// The chain of responsibility pattern has a // group of objects that are expected to between// them be able to solve a problem. // If the first Object can't solve it, it passes// the data to the next Object in the chain

public interface Chain { // Defines the next Object to receive the data // if this Object can't process it public void setNextChain(Chain nextChain);

// Either solves the problem or passes the data // to the next Object in the chain public void calculate(Numbers request); }

public class AddNumbers implements Chain{ private Chain nextInChain;

// Defines the next Object to receive the // data if this one can't use it public void setNextChain(Chain nextChain) { nextInChain = nextChain; }

// Here I define all of the objects in the chain Chain chainCalc1 = new AddNumbers(); Chain chainCalc2 = new SubtractNumbers(); Chain chainCalc3 = new MultNumbers(); Chain chainCalc4 = new DivideNumbers();

// Here I tell each object where to forward the // data if it can't process the request chainCalc1.setNextChain(chainCalc2); chainCalc2.setNextChain(chainCalc3); chainCalc3.setNextChain(chainCalc4);

// Define the data in the Numbers Object // and send it to the first Object in the chain Numbers request = new Numbers(4,2,"add");

// Calculation start from the beginning of the chain chainCalc1.calculate(request); }}

when to use chain of responsibility

You want to decouple a request's sender and receiver/handler.

Data driven. Based on the request data sent, the receiver/handler is picked.

Multiple objects, determined at runtime, are candidates to handle a request.