1
头图

written in front

  • Take notes on learning design patterns
  • Improve flexible use of design patterns

learning address

">https://www.bilibili.com/video/BV1G4411c7N4

">https://www.bilibili.com/video/BV1Np4y1z7BU

Reference article

http://c.biancheng.net/view/1317.html

project source code
https://gitee.com/zhuang-kang/DesignPattern

27. Chain of Responsibility Model

27.1 Definition and characteristics of the chain of responsibility model

The definition of the Chain of Responsibility mode: In order to avoid coupling the request sender with multiple request handlers, all request handlers are connected into one by remembering the reference of the next object through the previous object Chain; when a request occurs, the request can be passed along this chain until an object handles it.

Note: The chain of responsibility model is also called the chain of responsibility model.

In the chain of responsibility model, the customer only needs to send the request to the chain of responsibility, and does not need to care about the processing details of the request and the request delivery process, the request will be automatically delivered. So the chain of responsibility decouples the sender of the request from the handler of the request.

chain of responsibility model is an object behavior model, and its main advantages are as follows.

  1. Reduce the degree of coupling between objects. This mode makes it unnecessary for an object to know which object is processing its request and the structure of the chain, and the sender and receiver do not need to have clear information about each other.
  2. Enhance the scalability of the system. You can add new request processing classes as needed to meet the opening and closing principles.
  3. Enhanced flexibility in assigning responsibilities to objects. When the work flow changes, members in the chain can be dynamically changed or their order can be mobilized, and responsibilities can also be dynamically added or deleted.
  4. The chain of responsibility simplifies the connection between objects. Each object only needs to maintain a reference to its successor, and does not need to maintain a reference to all other processors, which avoids the use of numerous if or if···else statements.
  5. Responsibility sharing. Each class only needs to deal with the work that should be handled by itself, and pass on to the next object for completion that should not be handled. The scope of responsibility of each class is clarified and conforms to the single responsibility principle of the class.

The main disadvantages of

  1. There is no guarantee that every request will be processed. Since a request has no clear recipient, there is no guarantee that it will be processed, and the request may not be processed until it reaches the end of the chain.
  2. Compared with a longer chain of responsibility, the processing of requests may involve multiple processing objects, and system performance will be affected to a certain extent.
  3. The rationality of the establishment of the chain of responsibility is guaranteed by the client, which increases the complexity of the client, and may cause system errors due to the incorrect setting of the chain of responsibility, such as loop calls.

27.2 Structure and Implementation of the Chain of Responsibility Model

27.2.1 Structure of the Chain of Responsibility Model

  1. Abstract Handler (Handler) role: Define an interface for processing requests, including abstract processing methods and a subsequent connection.
  2. Concrete Handler role: to implement the processing method of the abstract handler, to determine whether the request can be processed, and if it can handle the request, it will be processed, otherwise the request will be forwarded to its successor.
  3. Client role: Create a processing chain, and submit a request to the specific handler object at the head of the chain. It does not care about the details of the processing and the delivery process of the request.

27.2.1 Code Implementation

Develop a leave process control system. Asking for leave of less than one day only requires the consent of the team leader; asking for leave of 1 to 3 days requires the approval of the department manager; requesting 3 to 7 days requires the consent of the general manager

Relationship class diagram

image

LeaveRequest

package com.zhuang.responsibility;

/**
 * @Classname LeaveRequest
 * @Description 请假条
 * @Date 2021/3/31 16:21
 * @Created by dell
 */

public class LeaveRequest {
    //姓名
    private String name;
    // 请假天数
    private int num;
    // 请假内容
    private String content;

    public LeaveRequest(String name, int num, String content) {
        this.name = name;
        this.num = num;
        this.content = content;
    }

    public String getName() {
        return name;
    }

    public int getNum() {
        return num;
    }

    public String getContent() {
        return content;
    }

}

Handler

package com.zhuang.responsibility;

/**
 * @Classname Handler
 * @Description 用一句话描述类的作用
 * @Date 2021/3/31 16:23
 * @Created by dell
 */

public abstract class Handler {
    protected final static int NUM_ONE = 1;
    protected final static int NUM_THREE = 3;
    protected final static int NUM_SEVEN = 7;

    //该领导处理的请假天数区间
    private int numStart;
    private int numEnd;


    //领导上还有领导
    private Handler nextHandler;

    //设置请假天数范围
    public Handler(int numStart) {
        this.numStart = numStart;
    }

    //设置请假天数范围
    public Handler(int numStart, int numEnd) {
        this.numStart = numStart;
        this.numEnd = numEnd;
    }

    //设置上级领导
    public void setNextHandler(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }

    //提交请假条
    public final void submit(LeaveRequest leaveRequest) {
        if (this.numStart == 0) {
            return;
        }
        //请假天数达到领导处理要求
        if (leaveRequest.getNum() >= this.numStart) {
            this.handleLeave(leaveRequest);

            //如果还有上级 并且请假天数超过当前领导的处理范围
            if (this.nextHandler != null && leaveRequest.getNum() > numEnd) {
                //继续提交
                this.nextHandler.submit(leaveRequest);
            } else {
                System.out.println("流程结束!!!");
            }
        }
    }

    //各级领导处理请假条方法
    protected abstract void handleLeave(LeaveRequest leave);

}

GroupLeader

package com.zhuang.responsibility;

/**
 * @Classname GroupLeader
 * @Description 小组长类
 * @Date 2021/3/31 16:33
 * @Created by dell
 */

public class GroupLeader extends Handler {
    //1-3天的假
    public GroupLeader() {
        super(Handler.NUM_ONE, Handler.NUM_THREE);
    }

    @Override
    protected void handleLeave(LeaveRequest leave) {
        System.out.println(leave.getName() + "请假" + leave.getNum() + "天," + leave.getContent() + "!");
        System.out.println("小组长审批通过:同意!");
    }
}

Manager

package com.zhuang.responsibility;

/**
 * @Classname Manager
 * @Description 部门经理类
 * @Date 2021/3/31 16:36
 * @Created by dell
 */

public class Manager extends Handler {
    //3-7天的假
    public Manager() {
        super(Handler.NUM_THREE, Handler.NUM_SEVEN);
    }

    @Override
    protected void handleLeave(LeaveRequest leave) {
        System.out.println(leave.getName() + "请假" + leave.getNum() + "天," + leave.getContent() + "!");
        System.out.println("部门经理审批通过:同意!");
    }
}

GeneralManager

package com.zhuang.responsibility;

/**
 * @Classname GeneralManager
 * @Description 总经理类
 * @Date 2021/3/31 16:38
 * @Created by dell
 */

public class GeneralManager extends Handler{
    //7天以上的假
    public GeneralManager() {
        super(Handler.NUM_THREE, Handler.NUM_SEVEN);
    }

    @Override
    protected void handleLeave(LeaveRequest leave) {
        System.out.println(leave.getName() + "请假" + leave.getNum() + "天," + leave.getContent() + "!");
        System.out.println("总经理审批通过:同意!");
    }
}

Client

package com.zhuang.responsibility;

/**
 * @Classname Client
 * @Description 责任链模式 测试类
 * @Date 2021/3/31 16:39
 * @Created by dell
 */

public class Client {
    public static void main(String[] args) {
        //请假条
        LeaveRequest leave = new LeaveRequest("小庄", 3, "出去旅游");

        //各位领导
        Manager manager = new Manager();
        GroupLeader groupLeader = new GroupLeader();
        GeneralManager generalManager = new GeneralManager();

        /*
        小组长上司是经理 经理上司是总经理
         */
        groupLeader.setNextHandler(manager);
        manager.setNextHandler(generalManager);

        //提交
        groupLeader.submit(leave);

    }
}

image

27.3 Application Scenarios of the Chain of Responsibility Model

  1. Multiple objects can handle a request, but which object handles the request is automatically determined at runtime.
  2. You can dynamically specify a group of objects to process the request, or add a new handler.
  3. It is necessary to submit a request to one of multiple processors without clearly specifying the request processor.

written at the end

  • If my article is useful to you, please give me some 👍, thank you 😊!
  • If you have any questions, please point them out in the comment area! 💪

康小庄
12 声望6 粉丝

代码不停,思考不止.