Design mode-Responsibility chain mode

Source: Internet
Author: User

Responsibility Chain (Chain of Responsibility) mode : The responsibility chain pattern is the behavior pattern of the object. Enables multiple objects to have the opportunity to process requests, thus avoiding direct coupling between the sender and the recipient of the request. Connect the objects as a chain and pass the request along this chain until an object has processed it. The responsibility chain model emphasizes that each object and its introduction to the next is used to form a chain, which uses this method to decouple the sender from the receiver, and the class diagram is as follows:

There are two roles that can be seen in the chain of responsibility Model: Abstract Processor (Handler) role: Defines the interface for a request. If necessary, you can define a method to set and return a reference to a home object. specific Processor (Concretehandler) role: If you can deal with the request, if unable to deal with, the request passed to the homes, let the under processing. This means that it handles requests that it can handle and can access its own homes. The test code for the above pattern is as follows:
Package Chainofresp;public abstract class Handler {  protected Handler successor;     public abstract void Handlerrequest (String condition);      Public Handler Getsuccessor () {    return successor;  }  public void Setsuccessor (Handler successor) {    this.successor = successor;  }}

Package chainofresp; public class ConcreteHandler1 extends Handler {  @Override public  void Handlerrequest (String condition) {    // If it is their own responsibility, to deal with their own, responsible for the treatment of the    condition.equals ("ConcreteHandler1") {System.out.println ("      ConcreteHandler1 Handled ");      return;    } else{      System.out.println ("ConcreteHandler1 passed");      Getsuccessor (). Handlerrequest (condition);    }  } }

Package chainofresp;  public class ConcreteHandler2 extends Handler {    @Override public  void Handlerrequest (String condition) {    //If it is your own responsibility, handle it on your own, and be responsible for passing it to the disposal if    (Condition.equals ("ConcreteHandler2")) {      System.out.println (" ConcreteHandler2 handled ");      return;    } else{      System.out.println ("ConcreteHandler2 passed");      Getsuccessor (). Handlerrequest (condition);    }  } }

Package Chainofresp;public class Concretehandlern extends Handler {  /**   * Here assume that n is the last node of the chain that must be disposed of   * in the actual case, There may be a ring, or a tree,   * This is not necessarily the last node.   * */    @Override public  void handlerrequest (String condition) {    System.out.println (" Concretehandlern handled ");}      }

Package chainofresp; public class Client {public   static void Main (string[] args) {      Handler handler1 = new ConcreteHandler1 ();    Handler handler2 = new ConcreteHandler2 ();    Handler Handlern = new Concretehandlern ();        Chain up    handler1.setsuccessor (handler2);    Handler2.setsuccessor (Handlern);        Assume that this request is ConcreteHandler2 's responsibility    handler1.handlerrequest ("ConcreteHandler2");}   }

For example, in the Toy Factory production workshop, the assembly line is a chain of responsibility, if a toy aircraft has a Shell assembly, engine assembly, propeller assembly, model Packer composition. When this object plane flows to who there, who is responsible for installing this part of his responsibility, this part of the installation is completed after the flow to the next step, knowing all the environment is complete. This is a generated chain of responsibility. There is also a quality testing chain, quality testing is divided into multiple parts, shell detection, engine detection, propeller detection, packaging testing. When the product is left to the inspector to detect the piece of their own responsibility, if there is a problem directly to carry out, if there is no problem, pass to the next inspector until all the tests are complete. These two are the chain of responsibility, but the difference is that the generation of the responsibility chain is handled by everyone and processed, and the quality inspection responsibility chain is judged, either disposed of, or not processed. This is the responsibility chain of two categories, the latter is called the pure responsibility chain, the former is called the impure responsibility chain, the pure responsibility chain in the actual application rarely exists, the common is the impure responsibility chain, the above model is simulates the pure responsibility chain to deal with.   Responsibility chain model in the reality of the use of many, common is the OA system in the workflow. The actual application in Java has a filter in the servlet (filter), the Struts2 Interceptor (Interceptor). Struts2 itself in the servlet is also in the form of filter, so the STRUTS2 structure diagram, you can clearly see the filter and interceptor the existence of these two chains.    can see that each node can do something, so it doesn't count as a pure chain of responsibility. In the above mentioned OA system, then we simulated the OA system in the absence of the approval process, if the employee direct boss for Team leader, team leader Direct Supervisor Project manager, Project manager Direct Boss Department manager, department manager Direct boss general manager. The company stipulated the following: Leave time is T, Time Unit day, shorthand d:t<  0.5d, team leader approval; T&GT;=0.5D,T&LT;2, project manager approval; T&GT;=2,T&LT;5 department manager approval; T&GT;=5 General manager approval Approval sequence diagram as follows:  in code description: 
Package chainofresp.example; Public abstract class Handler {  protected Handler Handler;   Public abstract Boolean approve (Double day);    Public Handler GetHandler () {    return Handler;  }  public void SetHandler (Handler Handler) {    this.handler = Handler;  }  }
Package Chainofresp.example;public class Groupleader extends Handler {  @Override public  Boolean approve ( Double day) {    if (day<0.5) {      System.out.println ("Team leader approval Pass");      return true;    } else {      System.out.println ("team leader passed to his boss");      Return GetHandler (). Approve (day);    }  } }

Package Chainofresp.example;public class Projectmanager extends Handler {  @Override public  Boolean approve ( Double day) {    if (day<2) {      System.out.println ("Project manager approval Pass");      return true;    } else {      System.out.println ("project manager passed to his boss");      Return GetHandler (). Approve (day);}}  

Package Chainofresp.example;public class Departmentmanager extends Handler {  @Override public  Boolean Approve (double day) {    if (day<5) {      System.out.println ("Department manager approval Pass");      return true;    } else {      System.out.println ("department manager passed to his boss");      Return GetHandler (). Approve (day);}}  

Package Chainofresp.example;public class CEO extends Handler {  @Override public  Boolean approve (Double day) { C22/>SYSTEM.OUT.PRINTLN ("approval by department manager");      return true;      }}

Package chainofresp.example; public class Client {public   static void Main (string[] args) {    //Create node    groupleader gl = new Groupleader ();    Projectmanager pm = new Projectmanager ();    Departmentmanager dm = new Departmentmanager ();    CEO CEO = new CEO ();    Establish responsibility chain    Gl.sethandler (PM);    Pm.sethandler (DM);    Dm.sethandler (CEO);        Apply to Team leader, request approval for 4-day holiday    gl.approve (4D);}   }

Operation Result:

Team leader passed it to his boss, the project manager passed it to his boss. Department manager approval through this simulation is an ideal state, so is a pure chain of responsibility, in practice, may team leader signed, the project manager signed ... A bunch of signatures, rather than not participating in the processing of requests. The advantage of the responsibility chain model is that the caller does not need to know the specific person to handle the request, and does not know the concrete structure of the chain, reduces the coupling degree of node domain node, and can dynamically modify the object responsibility in the chain at run time, enhances the flexibility of assigning responsibilities to the object; Have not been properly disposed of.

Design mode-Responsibility chain mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.