2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
The Chain of Responsibility Pattern is a behavioral design pattern that allows multiple objects to process requests in sequence, and each object can choose whether to process the request itself or pass it to the next object. This pattern provides greater flexibility and scalability by decoupling the sender and receiver of the request. The following is a detailed introduction to the Chain of Responsibility Pattern:
The core of the responsibility chain pattern is to design a request chain and the end mark of the chain. It connects multiple objects that process requests into a chain and allows the request to be passed on this chain until an object in the chain decides to process the request. The client that issues the request does not know which object in the chain will eventually process the request, which allows the system to dynamically reorganize and assign responsibilities without affecting the client.
Class Diagram:
The responsibility chain model mainly includes the following roles:
Abstract Handler: Defines an interface for handling requests. If necessary, the interface can define a method to set and return a reference to the next client. This role is usually implemented by an abstract class or interface.
Concrete Handler: After receiving the request, the specific processor can choose to process the request or pass it to the next client. Since the specific processor holds a reference to the next client, the specific processor can access the next client if necessary.
Client: Create a processing chain and submit a request to the specific processor object at the head of the chain.
The chain of responsibility pattern is applicable to the following scenarios:
Multiple objects work together to process a task: For example, in a multi-level approval system, the approval request is passed to the approver at the next level according to the approver's authority and level until the final approval result is obtained.
Dynamic combination processing flow: By flexibly configuring the responsibility chain, processing objects can be dynamically combined to achieve different processing flows.
Avoid direct coupling between senders and receivers of requests: By passing the request to the chain of responsibility, the request sender does not need to know the specific processing object, reducing the dependencies between objects.
The responsibility chain model is widely used in many fields, including but not limited to:
The following is a simple implementation example of the chain of responsibility pattern, which is used to process log messages and pass messages to different handlers according to the log level (such as DEBUG, INFO, WARN, ERROR):
- // 抽象处理者
- abstract class LogHandler {
- protected int level;
- protected LogHandler nextHandler;
-
- public void setNextHandler(LogHandler nextHandler) {
- this.nextHandler = nextHandler;
- }
-
- //这个是精髓:他除了处理自己的逻辑,还会调用nextHandler进行处理
- public void logMessage(int level, String message) {
- if (this.level <= level) {
- write(message);
- }
- if (nextHandler != null) {
- nextHandler.logMessage(level, message);
- }
- }
-
- abstract protected void write(String message);
- }
-
- // 具体处理者:ErrorLogHandler
- class ErrorLogHandler extends LogHandler {
- public ErrorLogHandler(int level) {
- this.level = level;
- }
-
- @Override
- protected void write(String message) {
- System.out.println("ErrorLogHandler: " + message);
- }
- }
-
- // 具体处理者:WarnLogHandler
- class WarnLogHandler extends LogHandler {
- public WarnLogHandler(int level) {
- this.level = level;
- }
-
- @Override
- protected void write(String message) {
- System.out.println("WarnLogHandler: " + message);
- }
- }
-
- // 具体处理者:InfoLogHandler
- class InfoLogHandler extends LogHandler {
- public InfoLogHandler(int level) {
- this.level = level;
- }
-
- @Override
- protected void write(String message) {
- System.out.println("InfoLogHandler: " + message);
- }
- }
-
- // 客户端代码
- public class ChainPatternDemo {
- private static LogHandler getChainOfLoggers() {
- // 创建链中的处理者
- LogHandler errorLogHandler = new ErrorLogHandler(3);
-
- LogHandler warnLogHandler = new WarnLogHandler(2);
- warnLogHandler.setNextHandler(errorLogHandler);
-
- LogHandler infoLogHandler = new InfoLogHandler(1);
- infoLogHandler.setNextHandler(warnLogHandler);
-
- return infoLogHandler;
- }
-
- public static void main(String[] args) {
- LogHandler loggerChain = getChainOfLoggers();
-
- loggerChain.logMessage(1, "This is an informational message.");
- loggerChain.logMessage(2, "This is a warning message.");
- loggerChain.logMessage(3, "This is an error message.");
- }
- }
In this example, we define three specific log handler classes (ErrorLogHandler
、WarnLogHandler
、InfoLogHandler
), which handle log messages of different levels. Each handler contains a level (level
) to determine whether messages of this level should be processed.logMessage
method, the request is passed to the first handler in the chain (infoLogHandler
), which decides whether to process the message based on its own level and processing logic, and then (if not) passes the request to the next handler in the chain. This process continues until the end of the chain or the request is processed.
Note that in a real application, you might need toLogHandler
The class adds more methods and properties to support more complex log processing logic and configuration. In addition, the log level is usually enumerated (enum
) instead of integers to improve code readability and maintainability.
The chain of responsibility pattern connects multiple objects that process requests into a chain and allows the request to be passed on the chain until an object on the chain decides to process the request, thereby achieving flexible request processing and system scalability.
If the responsibility chain pattern is useful to you, remember to like and collect it.