Chain of Responsibility Pattern
The Chain of Responsibility Pattern creates a chain of receiver objects for a request. This pattern decouples the sender and receiver of a request based on the type of request. This type of design pattern belongs to the behavioral pattern category.
The chain of responsibility pattern connects multiple handlers (processing objects) in a chain structure, so that the request is passed along the chain until a handler handles the request.
The chain of responsibility pattern allows multiple objects to have a chance to handle the request, thereby avoiding coupling between the sender and receiver of the request. These objects are connected into a chain, and the request is passed along the chain.
Introduction
Intent
Allow the request to be passed along the chain of handlers until it is handled..
Main problem solved
- Decouple the request sender and receiver, so multiple objects may receive the request, and the sender does not need to know which object will handle it.
Use Cases
- When multiple objects can handle a request, and which object handles it is determined at runtime.
- When a request needs to be submitted to one of multiple objects without explicitly specifying the receiver.
Implementation
- Define a handler interface: all handlers must implement the same interface.
- Create concrete handlers: concrete classes implementing the interface, containing request handling logic and a reference to the next handler in the chain.
Key code
- Handler interface: define a method for handling requests.
- ConcreteHandler class: implement the Handler interface, containing request handling logic and a reference to the next handler.
Application Example
- Drum pass (passing the parcel): the passing action in the game until the music stops.
- Event bubbling: in JavaScript, events start from the most specific element and propagate upward level by level.
- Web server: such as Apache Tomcat handling character encoding, Struts2 interceptors, and Servlet Filters.
Advantages
- Reduced coupling: decoupling between sender and receiver.
- Simplify objects: objects do not need to know the structure of the chain.
- Flexibility: dynamically add or remove responsibilities by changing the members or order of the chain.
- Easy to extend: it is convenient to add new request handling classes.
Disadvantages
- Request not handled: there is no guarantee that a request will be received by some handler in the chain.
- Performance Impact: may affect system performance, is difficult to debug, and may cause circular calls.
- Hard to observe: runtime characteristics are not obvious, which may hinder debugging.
Usage recommendation
- When handling a request, if there are multiple potential handlers, consider using the chain of responsibility pattern.
- Ensure that each handler in the chain clearly knows how to pass the request to the next link in the chain.
Notes
- In Java web development, the chain of responsibility pattern is widely used, such as filter chains, interceptors, etc.
structures
Mainly involves the following core roles:
-
Abstract Handler (Handler):
- Define an interface for handling requests, usually containing a method for handling requests (such as
handleRequest) and a reference to the next handler (successor).
-
Concrete Handler (ConcreteHandler):
- Implements the abstract handler interface, responsible for handling requests. If it can handle the request, it handles it directly; otherwise, it passes the request to the next handler.
-
Client (Client):
- Create handler objects and connect them into a chain of responsibility. Usually, the client only needs to send the request to the first handler in the chain, without caring about the specific processing of the request.
Create a class that implements
We create an abstract class AbstractLoggerwith detailed logging levels. Then we create three types of loggers, all extending AbstractLogger. Each logger checks whether the level of a message belongs to its own level; if so, it prints it accordingly, otherwise it does not print and passes the message to the next logger.
Step 1
Create the abstract logger class.
AbstractLogger.java
public
abstract
class
AbstractLogger
{
public
static
int
INFO
=
1
;
public
static
int
DEBUG
=
2
;
public
static
int
ERROR
=
3
;
protected
int
level
;
//
The next element in the chain of responsibility
protected
AbstractLogger
nextLogger
;
public
void
setNextLogger
(
AbstractLogger
nextLogger
)
{
this
.
nextLogger
=
nextLogger
;
}
public
void
logMessage
(
int
level
,
String
message
)
{
if
(
this
.
level
<=
level
)
{
write
(
message
)
;
}
if
(
nextLogger
!=
null
)
{
nextLogger
.
logMessage
(
level
,
message
)
;
}
}
abstract
protected
void
write
(
String
message
)
;
}
Step 2
Create concrete classes that extend the logger class.
ConsoleLogger.java
public
class
ConsoleLogger
extends
AbstractLogger
{
public
ConsoleLogger
(
int
level
)
{
this
.
level
=
level
;
}
@
Override
protected
void
write
(
String
message
)
{
System
.
out
.
println
(
"
Standard Console::Logger:
"
message
)
;
}
}
ErrorLogger.java
public
class
ErrorLogger
extends
AbstractLogger
{
public
ErrorLogger
(
int
level
)
{
this
.
level
=
level
;
}
@
Override
protected
void
write
(
String
message
)
{
System
.
out
.
println
(
"
Error Console::Logger:
"
message
)
;
}
}
FileLogger.java
public
class
FileLogger
extends
AbstractLogger
{
public
FileLogger
(
int
level
)
{
this
.
level
=
level
;
}
@
Override
protected
void
write
(
String
message
)
{
System
.
out
.
println
(
"
File::Logger:
"
message
)
;
}
}
Step 3
Create different types of loggers. Assign them different error levels, and set the next logger in each logger. The next logger in each logger represents a part of the chain.
ChainPatternDemo.java
public
class
ChainPatternDemo
{
private
static
AbstractLogger
getChainOfLoggers
(
)
{
AbstractLogger
errorLogger
=
new
ErrorLogger
(
AbstractLogger
.
ERROR
)
;
AbstractLogger
fileLogger
=
new
FileLogger
(
AbstractLogger
.
DEBUG
)
;
AbstractLogger
consoleLogger
=
new
ConsoleLogger
(
AbstractLogger
.
INFO
)
;
errorLogger
.
setNextLogger
(
fileLogger
)
;
fileLogger
.
setNextLogger
(
consoleLogger
)
;
return
errorLogger
;
}
public
static
void
main
(
String
[
]
args
)
{
AbstractLogger
loggerChain
=
getChainOfLoggers
(
)
;
loggerChain
.
logMessage
(
AbstractLogger
.
INFO
,
"
This is an information.
"
)
;
loggerChain
.
logMessage
(
AbstractLogger
.
DEBUG
,
"
This is a debug level information.
"
)
;
loggerChain
.
logMessage
(
AbstractLogger
.
ERROR
,
"
This is an error information.
"
)
;
}
}
Step 4
Run the program, output result:
Standard Console::Logger: This is an information.
File::Logger: This is a debug level information.
Standard Console::Logger: This is a debug level information.
Error Console::Logger: This is an error information.
File::Logger: This is an error information.
Standard Console::Logger: This is an error information.