Notes on the Chain of Responsibility Pattern of Design Patterns

illustrate

Record the writing method of learning design pattern-chain of responsibility pattern. The JDK version used is version 1.8.

Chain of Responsibility

Intent : Give multiple objects a chance to handle the request, thereby avoiding coupling between the sender and receiver of the request. These objects are connected into a chain and the request is passed along the chain until an object handles it.
Structure :
Insert image description here

in:

  • Handler defines an interface for processing requests; (optional) implements the successor chain.
  • ConcreteHandler handles the request it is responsible for; has access to its successors; if the request can be handled, handles it, otherwise forwards the request to the successor.
  • Client submits a request to the concrete handler (ConcreteHandler) object on the chain.

applicability:

  • There are multiple objects that can handle a request, and which object handles the request is automatically determined at runtime.
  • Want to submit a request to one of multiple objects without explicitly specifying the recipient.
  • The set of objects that can handle a request should be dynamically specified.

Table of contents

Insert image description here

Chain of Responsibility Pattern Example Class Diagram

Insert image description here

Use this UML class diagram to implement an example of the chain of responsibility pattern.

Leave requests

package com.example.deesign_patterns.responsibility;

//请假条类
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;
    }
}

abstract handler class

package com.example.deesign_patterns.responsibility;

//抽象处理者类
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;
    }

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

    //提交请求条
    public final void submit(LeaveRequest leave){
    
    
        //该领导进行审批
        this.handleLeave(leave);
        //判断是否有上级领导且该领导能否处理
        if(this.nextHandler!=null&&leave.getNum()>this.numEnd){
    
    
            //提交给上级领导进行审批
            this.nextHandler.submit(leave);
        }else {
    
    
            System.out.println("流程结束!");
        }
    }
}

Group leader category

package com.example.deesign_patterns.responsibility;

//小组长类(具体的处理者)
public class GroupLeader extends Handler{
    
    

    //定义小组长批准天数为1天
    public GroupLeader() {
    
    
        super(0,Handler.NUM_ONE);
    }

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

Department manager class

package com.example.deesign_patterns.responsibility;

//部门经理类(具体的处理者)
public class Manager extends Handler{
    
    

    //部门经理批准天数为1-3天
    public Manager() {
    
    
        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("部门经理审批:同意");
    }
}

General Manager

package com.example.deesign_patterns.responsibility;

//总经理类(具体的处理者)
public class GeneralManager extends Handler{
    
    

    //总经理批准天数为3-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("总经理审批:同意");
    }
}

Test class

package com.example.deesign_patterns.responsibility;

//测试类
public class Client {
    
    

    public static void main(String[] args) {
    
    
        //创建一个请假条对象
        LeaveRequest leave=new LeaveRequest("小明",7,"身体不适");
        //创建各级领导对象
        GroupLeader groupLeader=new GroupLeader();
        Manager manager=new Manager();
        GeneralManager generalManager=new GeneralManager();
        //设置处理者链
        groupLeader.setNextHandler(manager);
        manager.setNextHandler(generalManager);
        //小明提交请假申请
        groupLeader.submit(leave);
    }
}

Insert image description here

benefit:

  • Reduces the coupling between objects. This pattern reduces the coupling between request senders and receivers.
  • Enhanced system scalability. New request processing classes can be added as needed to meet the opening and closing principle.
  • Increased flexibility in assigning responsibilities to objects. When the workflow changes, members within the chain can be dynamically changed or their order can be modified, and responsibilities can also be added or deleted dynamically.
  • Chain of responsibility simplifies the connection between objects. An object only needs to maintain a reference to its successor, and does not need to maintain references to all other handlers, which avoids the use of numerous if or if...else statements.
  • Shared responsibilities. Each class only needs to handle the work it should handle, and the unprocessed work is passed to the next object for completion. The scope of responsibilities of each type is clearly defined, which is in line with the single responsibility principle of the class.

shortcoming:

  • 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.
  • Compared with a longer chain of responsibilities, the processing of requests may involve multiple processing objects, and system performance will be affected to a certain extent.
  • The rationality of the chain of responsibility establishment must be guaranteed by the client, which increases the complexity of the client. System errors may occur due to incorrect settings of the chain of responsibility, such as circular calls.

Guess you like

Origin blog.csdn.net/weixin_48040732/article/details/131358048