Technology Sharing

Design Pattern Exploration: Chain of Responsibility Pattern

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. What is the chain of responsibility model?

Chain of Responsibility Pattern Chain of Responsibility Pattern is a behavioral design pattern. It is defined as follows:

  • Avoid coupling the sender and receiver of a request, and give multiple objects a chance to handle the request.
  • The objects that receive the request are connected into a chain and the request is passed along the chain until an object is able to handle it.
    insert image description here

2. The role of the chain of responsibility model

  • Decouple requests from request processing to improve code scalability.

3. The structure of the chain of responsibility model

insert image description here

The responsibility chain model mainly includes the following roles:

  • Abstract Handler Role: Defines an interface for processing requests, including abstract processing methods and a successor connection (each handler in the chain has a member variable to store a reference to the next handler).
  • Concrete Handler Role: Implement the processing method of the abstract handler to determine whether the request can be processed. If it can be processed, process it; otherwise, transfer the request to its successor.
  • Client Role: Creates a processing chain and submits a request to the specific processor object at the head of the chain. It does not care about the processing details and the request transmission process.

In actual development, the chain of responsibility model may add a chain of responsibility manager to manage specific processors.

4. Application of the chain of responsibility model in actual development

In SpringBoot, there are many ways to practice the chain of responsibility pattern. The following is an example: multiple independent check logics for an order process.
insert image description here

4.1 Implementation 1
  1. Create Pojo, order object
public class OrderContext {
    private String seqId;
    private String userId;
    private Long skuId;
    private Integer amount;
    private String userAddressId;
    // Getters and setters
}