2015-08-13 23:54:40 +02:00
---
layout: pattern
title: Chain of responsibility
2021-06-24 15:57:20 +03:00
folder: chain-of-responsibility
permalink: /patterns/chain-of-responsibility/
2015-08-20 21:40:07 +02:00
categories: Behavioral
2021-05-19 10:49:05 -06:00
language: en
2015-09-22 18:25:56 +05:30
tags:
2019-12-13 22:22:11 +02:00
- Gang of Four
2015-08-13 23:54:40 +02:00
---
2016-01-03 21:14:30 +01:00
## Intent
2021-06-24 15:57:20 +03:00
2020-08-29 11:29:30 +03:00
Avoid coupling the sender of a request to its 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.
2015-08-13 23:54:40 +02:00
2017-09-19 23:20:40 +03:00
## Explanation
2021-06-24 15:57:20 +03:00
Real-world example
2017-09-19 23:20:40 +03:00
2020-08-29 11:29:30 +03:00
> The Orc King gives loud orders to his army. The closest one to react is the commander, then
2021-06-24 15:57:20 +03:00
> an officer, and then a soldier. The commander, officer, and soldier form a chain of responsibility.
2017-09-19 23:20:40 +03:00
In plain words
2020-08-29 11:29:30 +03:00
> It helps to build a chain of objects. A request enters from one end and keeps going from an object
> to another until it finds a suitable handler.
2017-09-19 23:20:40 +03:00
Wikipedia says
2020-08-29 11:29:30 +03:00
> In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of
> a source of command objects and a series of processing objects. Each processing object contains
> logic that defines the types of command objects that it can handle; the rest are passed to the
> next processing object in the chain.
2017-09-19 23:20:40 +03:00
**Programmatic Example**
2021-06-24 15:57:20 +03:00
Translating our example with the orcs from above. First, we have the `Request` class:
2017-09-19 23:20:40 +03:00
2018-03-28 01:35:43 -04:00
```java
2017-09-19 23:20:40 +03:00
public class Request {
private final RequestType requestType;
private final String requestDescription;
private boolean handled;
public Request(final RequestType requestType, final String requestDescription) {
this.requestType = Objects.requireNonNull(requestType);
this.requestDescription = Objects.requireNonNull(requestDescription);
}
public String getRequestDescription() { return requestDescription; }
public RequestType getRequestType() { return requestType; }
public void markHandled() { this.handled = true; }
public boolean isHandled() { return this.handled; }
@Override
public String toString() { return getRequestDescription(); }
}
public enum RequestType {
DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
}
```
2021-06-24 15:57:20 +03:00
Next, we show the request handler hierarchy.
2017-09-19 23:20:40 +03:00
2018-03-28 01:35:43 -04:00
```java
2021-03-13 13:19:21 +01:00
@Slf4j
2017-09-19 23:20:40 +03:00
public abstract class RequestHandler {
2020-07-30 20:28:47 +03:00
private final RequestHandler next;
2017-09-19 23:20:40 +03:00
public RequestHandler(RequestHandler next) {
this.next = next;
}
public void handleRequest(Request req) {
if (next != null) {
next.handleRequest(req);
}
}
protected void printHandling(Request req) {
LOGGER.info("{} handling request \"{}\"", this, req);
}
@Override
public abstract String toString();
}
public class OrcCommander extends RequestHandler {
public OrcCommander(RequestHandler handler) {
super(handler);
}
@Override
public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) {
printHandling(req);
req.markHandled();
} else {
super.handleRequest(req);
}
}
@Override
public String toString() {
return "Orc commander";
}
}
// OrcOfficer and OrcSoldier are defined similarly as OrcCommander
```
2021-06-24 15:57:20 +03:00
The Orc King gives the orders and forms the chain.
2017-09-19 23:20:40 +03:00
2018-03-28 01:35:43 -04:00
```java
2017-09-19 23:20:40 +03:00
public class OrcKing {
RequestHandler chain;
public OrcKing() {
buildChain();
}
private void buildChain() {
chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null)));
}
public void makeRequest(Request req) {
chain.handleRequest(req);
}
}
```
2021-06-24 15:57:20 +03:00
The chain of responsibility in action.
2017-09-19 23:20:40 +03:00
2018-03-28 01:35:43 -04:00
```java
2019-11-12 22:12:47 +02:00
var king = new OrcKing();
2021-06-24 15:57:20 +03:00
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner"));
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
```
The console output.
```
Orc commander handling request "defend castle"
Orc officer handling request "torture prisoner"
Orc soldier handling request "collect tax"
2017-09-19 23:20:40 +03:00
```
2015-08-13 23:54:40 +02:00
2019-12-07 20:01:13 +02:00
## Class diagram
2020-08-29 11:29:30 +03:00
2021-06-24 15:57:20 +03:00

2019-12-07 20:01:13 +02:00
2016-01-03 21:14:30 +01:00
## Applicability
2020-08-29 11:29:30 +03:00
2016-01-03 21:14:30 +01:00
Use Chain of Responsibility when
2015-08-13 23:54:40 +02:00
2020-08-29 11:29:30 +03:00
* More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically.
* You want to issue a request to one of several objects without specifying the receiver explicitly.
* The set of objects that can handle a request should be specified dynamically.
2015-08-13 23:54:40 +02:00
2021-06-24 15:57:20 +03:00
## Known uses
2015-08-13 23:54:40 +02:00
* [java.util.logging.Logger#log() ](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29 )
2015-08-15 18:03:05 +02:00
* [Apache Commons Chain ](https://commons.apache.org/proper/commons-chain/index.html )
2016-08-20 20:49:28 +05:30
* [javax.servlet.Filter#doFilter() ](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain- )
2015-09-22 18:25:56 +05:30
2016-01-03 21:14:30 +01:00
## Credits
2015-09-22 18:25:56 +05:30
2020-07-06 13:31:07 +03:00
* [Design Patterns: Elements of Reusable Object-Oriented Software ](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59 )
2020-07-07 18:05:11 +03:00
* [Head First Design Patterns: A Brain-Friendly Guide ](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b )