Responsibility chain pattern of Java design pattern

Keywords: Java Back-end

Responsibility chain model

  • Business requirements:
    OA system procurement approval requirements (Procurement approval items of school OA system):
    • Purchaser purchases teaching equipment
    • If the amount is less than 5000, it shall be approved by the Dean [0 < = x < = 5000]
    • If the amount is less than 10000, it shall be approved by the president [5000 < x < = 10000]
    • If the amount is less than 30000, it shall be approved by the vice president [10000 < x < = 30000]
    • If the amount exceeds 30000, it shall be approved by the president [30000 < x]
      Please design procedures to complete the procurement approval items.
  • Solution:
    • Traditional scheme:
      • Method: after a request is received, the approver is called to complete the approval according to the purchase amount. (use [if – eles if eles] | [switch] to judge the amount)
      • Problem analysis: the client uses branch judgment to process different purchase requests, so there are the following problems:
        • If the approved amount of personnel at all levels changes, the amount at the client also needs to change
        • The client must clearly know how many approval levels and accesses there are. In this way, there is a strong coupling relationship between a purchase request processing and approver, which is not conducive to code expansion and maintenance
      • Solution: responsibility chain model
    • Chain of Responsibility pattern
      • Basic introduction
        • It is also called responsibility chain model
        • A chain of recipient objects is created for the request. This mode decouples the sender and receiver of the request.
        • In the responsibility chain pattern, each recipient usually contains a reference to another recipient. If an object cannot process the request, it will pass the same request to the next recipient, and so on.
      • Schematic class diagram
        Multiple objects have the opportunity to process the request, so as to avoid the coupling relationship between the requesting sender and receiver. Connect the object into a chain and pass the request along the chain until an object handles it.
        • Handler: an abstract handler that defines an interface for processing requests and contains another handler
        • ConcreteHandlerA and ConcreteHandlerB are specific handlers. They handle the requests they are responsible for and can access their successors (i.e. the next handler). If they can handle the current request, they will handle it. Otherwise, they will hand over the request to the successors for processing, so as to form a responsibility chain
        • Request: contains many attributes, representing a request
      • Business class diagram
      • code implementation
        • Create a request processing object (PurchaseRequest.java)

          package ltd.huazhongyang.responsibilitychain;
          /**
           * Request class
           */
          public class PurchaseRequest {
              /**
               * Request type
               */
              private int type = 0 ;
              /**
               * Requested amount
               */
              private  double price = 0.0 ;
              /**
               * Request number
               */
              private int id = 0 ;
              //constructor 
              public PurchaseRequest(int type,  double price, int id) {
                  this.type = type;
                  this.price = price;
                  this.id = id;
              }
              public int getType() {
                  return type;
              }
              public double getPrice() {
                  return price;
              }
              public int getId() {
                  return id;
              }
          }
          
        • Create approver abstract class

          package ltd.huazhongyang.responsibilitychain;
          
          /**
           * Approver abstract class
           */
          public abstract class Approver {
          
              /**
               * Next processor
               */
              private Approver approver ;
          
              /**
               * name
               */
              String name ;
          
              public Approver(String name ){
                  this.name = name ;
              }
          
              /**
               *
               * @param approver Next processor
               */
              public void setApprover(Approver approver) {
                  this.approver = approver;
              }
          
              /**
               *
               * @return Return to next processor
               */
              public Approver getApprover() {
                  return approver;
              }
          
              /**
               * The method of processing the approval request obtains a request. The processing is completed by subclasses, so the method is made abstract
               */
              public abstract  void processRequest(PurchaseRequest purchaseRequest);
          }
          
        • Create a class with the approver as the director, and inherit the abstract class of Approver.java

          package ltd.huazhongyang.responsibilitychain;
          
          public class DepartmentApprover extends Approver{
          
              public DepartmentApprover(String name) {
                  super(name);
              }
          
              @Override
              public void processRequest(PurchaseRequest purchaseRequest) {
                  System.out.println("The amount is:["+String.valueOf(purchaseRequest.getPrice())+"]");
                  if (purchaseRequest.getPrice() < 5000){
                      System.out.println("Request number:id = "+purchaseRequest.getId()+" Be[ "+this.name+" ]handle");
                  }else {
                      System.out.println("-->"+this.name+":The request cannot be processed and is handed over to the next level to process the request");
                      super.getApprover().processRequest(purchaseRequest);
                  }
          
              }
          }
          
          
        • Create a class with the approver as the dean and inherit the Approver.java abstract class

          package ltd.huazhongyang.responsibilitychain;
          
          public class CollegeApprover extends Approver{
          
              public CollegeApprover(String name) {
                  super(name);
              }
          
              @Override
              public void processRequest(PurchaseRequest purchaseRequest) {
                  System.out.println("The amount is:["+String.valueOf(purchaseRequest.getPrice())+"]");
                  if (5000 <= purchaseRequest.getPrice() && purchaseRequest.getPrice() < 10000){
                      System.out.println("Request number:id = "+purchaseRequest.getId()+" Be[ "+this.name+" ]handle");
                  }else {
                      System.out.println("-->"+this.name+":The request cannot be processed and is handed over to the next level to process the request");
                      super.getApprover().processRequest(purchaseRequest);
                  }
          
              }
          }
          
        • Create a class with the approver as the vice president, and inherit the approval Approver.java abstract class

          package ltd.huazhongyang.responsibilitychain;
          
          public class ViceSchoolMasterApprover extends Approver{
          
              public ViceSchoolMasterApprover(String name) {
                  super(name);
              }
          
              @Override
              public void processRequest(PurchaseRequest purchaseRequest) {
                  System.out.println("The amount is:["+String.valueOf(purchaseRequest.getPrice())+"]");
                  if (10000 <= purchaseRequest.getPrice() && purchaseRequest.getPrice() < 30000){
                      System.out.println("Request number:id = "+purchaseRequest.getId()+" Be[ "+this.name+" ]handle");
                  }else {
                      System.out.println("-->"+this.name+":The request cannot be processed and is handed over to the next level to process the request");
                      super.getApprover().processRequest(purchaseRequest);
                  }
          
              }
          }
          
        • Create a class with the approver as the principal, and inherit the Approver.java abstract class

          package ltd.huazhongyang.responsibilitychain;
          
          public class ViceSchoolMasterApprover extends Approver{
          
              public ViceSchoolMasterApprover(String name) {
                  super(name);
              }
          
              @Override
              public void processRequest(PurchaseRequest purchaseRequest) {
                  System.out.println("The amount is:["+String.valueOf(purchaseRequest.getPrice())+"]");
                  if (10000 <= purchaseRequest.getPrice() && purchaseRequest.getPrice() < 30000){
                      System.out.println("Request number:id = "+purchaseRequest.getId()+" Be[ "+this.name+" ]handle");
                  }else {
                      System.out.println("-->"+this.name+":The request cannot be processed and is handed over to the next level to process the request");
                      super.getApprover().processRequest(purchaseRequest);
                  }
          
              }
          }
          
        • Create startup class

          package ltd.huazhongyang.responsibilitychain;
          
          public class Client {
              public static void main(String[] args) {
                  PurchaseRequest purchaseRequest = new PurchaseRequest(1, 21000, 1);
                  //Create relevant approvers
                  DepartmentApprover departmentApprover = new DepartmentApprover("Director Zhang");
                  CollegeApprover collegeApprover = new CollegeApprover("President Li");
                  ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("Vice president Wang");
                  SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("Headmaster Zhao");
          
                  //You need to set the next of each approval level (handler:)
                  departmentApprover.setApprover(collegeApprover);
                  collegeApprover.setApprover(viceSchoolMasterApprover);
                  viceSchoolMasterApprover.setApprover(schoolMasterApprover);
                  schoolMasterApprover.setApprover(departmentApprover);
          
                  schoolMasterApprover.processRequest(purchaseRequest);
          
              }
          
          }
          
        • test result

Posted by GiaTuan on Fri, 05 Nov 2021 22:23:23 -0700