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
2. Specific processors
3. Client
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