Location>code7788 >text

Chain of responsibility model

Popularity:80 ℃/2024-12-19 06:31:20
chain of responsibility(Chain of Responsibility)The model belongs to thebehavioralOne of the models.

The chain-of-responsibility model is a model for processing requests that gives multiple processors the opportunity to process the request until one of them succeeds. Each processor contains a reference to the next processor, thus forming a chain structure. The chain-of-responsibility pattern combines multiple processorslink up into a chain, and then let the request pass up the chain.

Financial Approval is a chain of responsibility pattern. Interceptor, Filter is also a chain of responsibility that not only allows each Handler to have a chance to process the request, but also allows the request to bepass on to sb elseGive the next Handler.

The chain-of-responsibility pattern is often used to intercept, preprocess requests.

The chain of responsibility model usually has the following components:

  • Abstract Handler (Handler): defines an interface for handling requests and provides a method for setting the next handler, typically an abstract class or interface.
  • ConcreteHandler: implements the logic for handling requests. Decides whether to process the request or pass it to the next handler based on the conditions.
  • Client: creates and assembles the chain of responsibility and issues the request.

Suppose there is a system that needs to handle user requests at different levels (e.g., regular user, manager, director). Each level of handler only handles requests that it can handle, and requests that cannot be handled are passed on to a higher level handler.

1. Abstract handlers

// Abstract handler
abstract class Handler {
    protected Handler nextHandler; // Next processor

public void setNextHandler(Handler nextHandler) {
         = nextHandler;
    }

    // Abstract method to handle requests
public abstract void handleRequest(int level);
}

2. Specific processors

// Specific processors: general user processors
class UserHandler extends Handler {
    @Override
    public void handleRequest(int level) {
        if (level <= 1) { // Normal users can only process requests of level 1
            ("UserHandler: Handling request with level " + level);
        } else if (nextHandler != null) {
            ("UserHandler: Cannot handle. Passing to next handler.");
            (level); // Forward the request
        }
    }
}

// Specific processor: Manager Processor
class ManagerHandler extends Handler {
    @Override
    public void handleRequest(int level) {
        if (level <= 2) { // Managers are able to handle requests of levels 1 and 2
            ("ManagerHandler: Handling request with level " + level);
        } else if (nextHandler != null) {
            ("ManagerHandler: Cannot handle. Passing to next handler.");
            (level); // Forward the request
        }
    }
}

// Specific processors: Superintendent processors
class DirectorHandler extends Handler {
    @Override
    public void handleRequest(int level) {
        if (level <= 3) { // The Director General is able to handle requests of levels 1, 2 and 3.
            ("DirectorHandler: Handling request with level " + level);
        } else {
            ("DirectorHandler: Cannot handle. Request denied.");
        }
    }
}

3. Client

// Client Code
public class Client {
    public static void main(String[] args) {
        // Create handlers
Handler userHandler = new UserHandler();
        Handler managerHandler = new ManagerHandler();
        Handler directorHandler = new DirectorHandler();

        // Set up the chain of responsibility: User -> Manager -> Director
        (managerHandler).
        (directorHandler).

// Send a request
        ("Request with level 1:");
        (1); // General user handling

        ("\nRequest with level 2:");
        (2); // Managerial processing

        ("\nRequest with level 3:");
        (3); // General Manager Processing

        ("\nRequest with level 4:");
        (4); // Can't handle it.
    }
}

chain-of-responsibility modeladvantages and disadvantages

Pros:

  • Requests are decoupled from handlers: the client doesn't need to care which handler handles the request.
  • High flexibility: It is very easy to extend the processors by dynamically combining the chain of processors. It is very easy to add new processors or rearrange processors.
  • Clear segregation of duties: each handler focuses on his or her own duties, in line with the single duty principle.

Drawbacks:

  • Chain may be too long: If the chain is too long, performance may be affected.
  • Debugging is difficult: the chained structure may make the flow of requests not easy to trace.

Behavioral patterns are primarily concerned with algorithms and the distribution of responsibilities among objects. Behavioral patterns can describe how a group of objects should collaborate to accomplish an overall task.

Everyone is fighting to swim through the deep waters of life. -- Smokey Sandy Jiuzhou