This is the 18th day of my participation in the August Genwen Challenge.More challenges in August

Today we come to learn, use frequency is very high, and the actual combat is relatively strong a mode —- combination mode. I’m going to talk a lot about Java design patterns this month. Click on your avatar and follow my column. I’ll keep updating.

Singletons of design patterns

Factory patterns for design patterns

The Builder pattern of design patterns

Proxy patterns for design patterns

Visitor patterns for design patterns

Adapter pattern for design pattern

Design pattern of the command pattern

Java state pattern | monitoring state change anytime and anywhere

Java observer pattern | how to notice things change

Java mode | how to record history information memorandum

Java iterator pattern model | how to access each element

Java the flyweight pattern | how to share the object

Java interpreter pattern | custom rules implementation logic

The Java bridge model | abstract binding with different implementations

Java facade pattern | how to improve the high availability of the interface

Updates continue at……

Without further ado, let’s get to the point

Chain of Responsibility model

The chain of responsibility model, which is important in this chain, from top to bottom, is A chain call, A calls B,B calls C.

Official definition: Avoid coupling the sender of a request to its receiver by providing multiple objects with the opportunity to process the request. The link receives the object and passes the request along the chain until the object processes it.

Note: A key point in the definition is to build a processing pipeline to process a request multiple times.

A few days ago, I encountered a scene in JINGdong. The earphone I bought last year was broken, and it was within its validity period today. After negotiation, I applied for after-sales service in Jingdong. I observed his condition carefully. I apply for after sales and customer service to call me call jingdong service is really good, have to say), will open the first order system query you provide order information and confirm whether it is right, to make sure before using logistics system notification express little elder brother door, Courier will return after little elder brother to take goods warehouse system to confirm, and inform the commodity system… Such a process is the real application of the chain of responsibility model.

In our daily development, A classic use scenario is the judgment of parameters, for example, we need to judge whether parameter A meets the conditions, whether parameter B meets the conditions, and then C judge, if both meet, and then go down to execute the relevant logic.

Let’s look at the picture below

From this figure, we can see that the chain of responsibility model actually has only two key roles.

  • Handler: Can be an interface that receives requests and dispatches them to a Handler chain (essentially an array linked list), in which the first Handler in the chain is placed at the beginning of the processing.

  • Concrete processing classes (HandlerA, B, C) : Concrete processing of requests in chain order.

Let’s use a real-world scenario to demonstrate the code

The code shown

Let me demonstrate the code using the scenario where our company submits a leave application at Dingding

We can see that after the cc’s approval, it is forwarded to the immediate supervisor and then to the hr specialist

// Leave entity
@Builder
public class LeaveRequest {
    / / number of days
    private int leaveDays;

    / / name
    private String name;
    
    // The reason for the leave
    private String reason;
}

Copy the code

// Leave responsibility chain abstract processing class
public class AbstractLeaveHandler {
    
    // Name of the leader
    protected String handlerName;

    // Next processing node (i.e., higher level leader)
    protected AbstractLeaveHandler nextHandler;

    // Set the next node
    protected void setNextHandler(AbstractLeaveHandler handler){
        this.nextHandler = handler;
    }

    // Handle leave requests, subclass implementation
    protected void handlerRequest(LeaveRequest request){}}Copy the code

Cc person (usually personnel department)

// copy the sender to receive
public class CCLeaveHandler extends AbstractLeaveHandler{
    public CCLeaveHandler(String name) {
        this.handlerName = name;
    }

    @Override
    protected void handlerRequest(LeaveRequest request) {
        Leave is not allowed after 10 days
        if(request.getLeaveDays() > 10){
            System.out.println("抄送人:" + handlerName + ", has been processed; The process ends.");
            return;
        }
        if(null! =this.nextHandler){
              // Approve and pass to the next responsibility chain
            this.nextHandler.handlerRequest(request);
        }else{
            System.out.println("Refuse!); }}}Copy the code

Direct supervisor (department direct leader)

// Direct supervisor
public class DirectLeaderLeaveHandler extends AbstractLeaveHandler{
    public DirectLeaderLeaveHandler(String name) {
        this.handlerName = name;
    }

    @Override
    protected void handlerRequest(LeaveRequest request) {
        System.out.println("Direct leadership :" + handlerName + ", start processing leave.");
    
        if(null! =this.nextHandler){
              // Approve and pass to the next responsibility chain
            this.nextHandler.handlerRequest(request);
        }else{
            System.out.println("Refuse!); }}}Copy the code

Human commissioner


//hr
public class HRLeaveHandler extends AbstractLeaveHandler{
    public HRLeaveHandler(String name) {
        this.handlerName = name;
    }

    @Override
    protected void handlerRequest(LeaveRequest request) {
        System.out.println("Human Resources Specialist :" + handlerName + ", has been processed; The process ends.");
        
        if(null! =this.nextHandler){
              / / approval
            this.nextHandler.handlerRequest(request);
        }else{
            System.out.println("Execution complete!"); }}}Copy the code

public class DingDingTest {
    public static void main(String[] args) {
        LeaveRequest request = LeaveRequest.builder().leaveDays(20).name("Xiao Ming").build();


        CCLeaveHandler cc = new CCLeaveHandler("Cc Xiao Li");
        DirectLeaderLeaveHandler directLeaderLeaveHandler = new DirectLeaderLeaveHandler("Direct leader, Mr. Wang.");
        HRLeaveHandler hrLeaveHandler = new HRLeaveHandler("Hr specialist, Xiao Guo."); cc.setNextHandler(deptManagerLeaveHandler); directLeaderLeaveHandler.setNextHandler(gManagerLeaveHandler); hrLeaveHandler.handlerRequest(request); }}Copy the code

As you can see from this code implementation, the chain of responsibility pattern is very simple, with each specific processing class being stored in the next processing class after it. When the processing is complete, the next processing class is called until the last processing class does not set the next processing class, at which point the processing chain is complete.

The chain of responsibility mode is just like the assembly line operation in a factory. It is implemented according to a standardized process. It is used in chained scenarios such as rule filtering and Web request protocol parsing to complete the processing of the whole process by splitting different processing nodes.

Responsibility chain mode is also widely used in actual code. And easy to understand.

OK, that’s the end of the code for today, so let’s wrap it up

conclusion

Why the chain of Responsibility model?

  • The first is to decouple users from the vast processes behind the scenes

  • Second, in order to dynamically change the processing object in the process processing. For example, in the process of asking for leave, the applicant will generally submit the application to the direct leader for approval, but sometimes the direct leader may not be able to carry out the approval operation, so the system can change the approver to another approver, so as not to block the approval process of asking for leave.

As for the advantages, I personally think that 1. It enhances the independence of responsibility of specific processing classes

2. This avoids using numerous if or if· else statements. It simplifies the complexity of correlative processing between objects. Each object stores only one reference to its successors and does not need to keep references to all other handlers,

There are drawbacks, in which case the class may increase. Second, the difficulty of debugging increases, there are problems, debugging is not good debugging. Third, it will also affect performance to some extent.

Responsibility chain in Netty

Just to mention a little bit, the awesome framework in Netty is also useful for responsibility chains. You can go down to understand, here will be behind the Netty will talk about

Channel pipeline responsibility chain in Netty: A pipeline pipeline holds all processor information for the channel. When a channel is created, a proprietary pipeline is automatically created. Inbound and outbound events call handlers on the pipeline

Bosom friend outside the lines

Thank you for reading, if you feel that you have learned something, please like, follow.

I have included this chapter in the topic, click on the topic below, pay attention to the column, I will publish dry goods every day, this month I will continue to input design mode.

Come on! See you next time!