Interviewer: What is the chain of responsibility model?

Preface

Hello everyone, I am a smart programmer . I introduced the singleton model in the last issue . Interested friends can read the previous sharing. Next, I will introduce to you another design pattern commonly used in work: the chain of responsibility pattern .

definition

What is a chain of responsibility? What are its characteristics?

The chain of responsibility pattern is a behavioral design pattern. In the chain of responsibility pattern, each object holds a reference to the next object to be processed, thus forming a chain. When the client initiates a request, the request will be passed along this chain, and each object will have a chance to handle the request. This allows the system to dynamically reorganize and allocate responsibilities without affecting the client.

The specific process is as follows:

Insert image description here

Application scenarios

  1. OA approval flow (such as initiating a vacation process, and determining which department leaders the current process needs to go to for approval based on the number of days of vacation)
  2. Filter filter (such as the account registration process, which needs to pass the legality verification of account number, password, etc.)

Method to realize

  • Demand background

Please design an employee vacation approval process. When the employee's vacation days are <= 1, the direct leader will approve it. When the vacation days are <= 2, the direct boss and the first-level department leader will approve them respectively. When the vacation days are >= 3, the approval process will be done respectively. Approval shall be subject to direct leadership, first-level department leaders, and leaders in charge.

First construct a request body RequestParam , including the applicant's name and the number of days of vacation.

/**
 * 审批请求体
 * @author coder_smart
 */
@Getter
@Setter
public class RequestParam {

    // 申请人
    private String name;

    // 休假时间
    private int time;

    public RequestParam(String name, int time) {
        this.name = name;
        this.time = time;
    }

    public RequestParam() {}
}

This is how you might write your code without using any fancy tricks.

public class Main{
    
    
    public static void main(String[] args) {
    
    
        // 初始化请求参数
        RequestParam requestParam = new RequestParam("张三", 3);

        if (requestParam.getTime() >= 1) {
    
    
            // 直接领导审批
            if (requestParam.getTime() >= 2) {
    
    
                // 一级部门领导审批
                if (requestParam.getTime() >= 3) {
    
    
                    // 分管领导审批
                }
            }
        }
    }
}

It can be clearly seen that each processing logic is surrounded by an if branch. When the business requirements are not complex or the number of processing nodes is not large, there is no problem at all. However, if the product manager proposes a small Opinion, when the number of vacation days is equal to 0.5, it will be approved by HR. When the number of vacation days is equal to 2.5, it will be approved by the second-level department leader. At this time, you have to change the nested if branch code, which greatly reduces the readability of the code. and scalability.

  • Transformation using the chain of responsibility model
/**
 * 抽象审批类
 * @author coder_smart
 */
public abstract class AuditHandler {
    
    
    // 下一个处理节点
    protected AuditHandler nextAuditHandler;

    // 设置下一个处理节点
    public void setNextAuditHandler(AuditHandler nextAuditHandler) {
    
    
        this.nextAuditHandler = nextAuditHandler;
    }

    // 抽象方法,子类实现各自处理的逻辑
    public abstract void audit(RequestParam requestParam);
}

The abstract approval class AuditHandler contains the reference nextAuditHandler of the next processor , which is injected through the setNextAuditHandler method, thus forming a chain. The abstract audit method uses the implementation class of each processor to implement its own approval logic.

/**
 * 直接领导审批处理类
 * @author coder_smart
 */
public class FirstLeaderAuditHandler extends AuditHandler{
    
    

    @Override
    public void audit(RequestParam requestParam) {
    
    
        System.out.print("start");
        System.out.print("---> 直接领导审批 ");
        if (requestParam.getTime() <= 1) {
    
    
            // do Something
            System.out.print("---> end");
            return;
        }
        nextAuditHandler.audit(requestParam);
    }
}
/**
 * 一级部门领导审批处理类
 * @author coder_smart
 */
public class SecondLeaderAuditHandler extends AuditHandler{
    
    

    @Override
    public void audit(RequestParam requestParam) {
    
    
        System.out.print("---> 一级部门领导审批 ");
        if (requestParam.getTime() <= 2) {
    
    
            // do Something
            System.out.print("---> end");
            return;
        }
        nextAuditHandler.audit(requestParam);
    }
}
/**
 * 分管领导审批处理类
 * @author coder_smart
 */
public class ThirdLeaderAuditHandler extends AuditHandler{
    
    

    @Override
    public void audit(RequestParam requestParam) {
    
    
        // do Something
        System.out.print("---> 分管部门领导审批 ");
        System.out.print("---> end");
        return;
    }
}
/**
 * 客户端
 *
 * @author coder_smart
 */
public class Main {
    
    
    public static void main(String[] args) {
    
    

        // 初始化请求参数
        // RequestParam requestParam = new RequestParam("张三", 1);
        // RequestParam requestParam = new RequestParam("张三", 2);
        RequestParam requestParam = new RequestParam("张三", 3);

        // 构建各处理节点对象
        AuditHandler firstLeaderHandler = new FirstLeaderAuditHandler();
        AuditHandler secondLeaderHandler = new SecondLeaderAuditHandler();
        AuditHandler thirdLeaderHandler = new ThirdLeaderAuditHandler();

        // 组装成责任链
        firstLeaderHandler.setNextAuditHandler(secondLeaderHandler);
        secondLeaderHandler.setNextAuditHandler(thirdLeaderHandler);

        // 开始审批
        firstLeaderHandler.audit(requestParam);
        
        // console log
        // time=1, start---> 直接领导审批 ---> end
        // time=2, start---> 直接领导审批 ---> 一级部门领导审批 ---> end
        // time=3, start---> 直接领导审批 ---> 一级部门领导审批 ---> 分管部门领导审批 ---> end
    }
}

Summarize

In the process of work, friends, please do not use design patterns in your own business code just to show off your skills. A good design pattern is a pattern that is suitable for the current business.

There are many types of design patterns, and the responsibility chain is the most interesting one to me, and it is worth learning.

If this article is helpful to you, please click three times to like , collect and watch it !

想更深入的了解设计模式原理以及相关面试题,更多详细资料请见:https://cloud.fynote.com/share/d/qinfK72

おすすめ

転載: blog.csdn.net/qq_41917138/article/details/126191637
おすすめ