Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Chain of Responsibility Pattern

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

Use Cases

Implementation

Key code

Application Example

  1. Drum pass (passing the parcel): the passing action in the game until the music stops.
  2. Event bubbling: in JavaScript, events start from the most specific element and propagate upward level by level.
  3. Web server: such as Apache Tomcat handling character encoding, Struts2 interceptors, and Servlet Filters.

Advantages

  1. Reduced coupling: decoupling between sender and receiver.
  2. Simplify objects: objects do not need to know the structure of the chain.
  3. Flexibility: dynamically add or remove responsibilities by changing the members or order of the chain.
  4. Easy to extend: it is convenient to add new request handling classes.

Disadvantages

  1. Request not handled: there is no guarantee that a request will be received by some handler in the chain.
  2. Performance Impact: may affect system performance, is difficult to debug, and may cause circular calls.
  3. Hard to observe: runtime characteristics are not obvious, which may hinder debugging.

Usage recommendation

Notes

structures

Mainly involves the following core roles:

- define an interface for handling requests, usually containing a method for handling requests (such as `handleRequest`) and a reference to the next handler (successor). - 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. - 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.