Example explains the application of responsibility chain pattern in Java design pattern programming _java

Source: Internet
Author: User

definition: enables multiple objects to have the opportunity to process requests, thereby avoiding coupling between the sender and receiver of the request. Connect the objects into a chain and pass the request along the chain until an object handles it.
Type: behavior class pattern
class Diagram:

First look at a piece of code:

public void Test (int i, request request) { 
  if (i==1) { 
    handler1.response (request); 
  } else if (i = = 2) { 
    handler2.response (request); 
  } else if (i = = 3) { 
    handler3.response (request); 
  } else if (i = = 4) { 
    handler4.response (request); 
  } else{ 
    Handler5.response (request); 
  } 
 

The business logic of the

       code is this, with two parameters: integer I and a request requests, depending on the value of I to decide who will process the request, if i== 1, by Handler1 to deal with, if i==2, by Handler2 to deal with, and so on. In programming, this method of dealing with the business is very common, all the classes that handle the request have if...else ... Conditional judgment statement is linked to a chain of responsibility to deal with the request, I believe we are often used. The advantages of this approach are straightforward, straightforward, and easier to maintain, but there are a few more troubling problems with this approach:
Code bloat: The decision conditions in the actual application are usually not so simple as to determine whether it is 1 or 2, and may require complex computations. may need to query the database and so on, this will have a lot of extra code, if the judgment condition is more, then this if...else ... The statement is basically impossible to read.
High coupling: If we want to continue adding the class that processes the request, we continue to add the else if decision condition; In addition, the order of this condition is written dead, and if you want to change the order, you can only modify the conditional statement.
        Since we are clear about the shortcomings, we must find a way to solve them. The business logic of this scenario is simple: if the condition 1 is met, it is handled by Handler1, is not satisfied, is passed down, if the condition 2 is met, then the Handler2 is processed, the unsatisfied continues to pass down, and so on until the condition is finished. In fact, the improvement of the method is also very simple, that is, to determine the conditions of the part of the processing class, this is the principle of responsibility-linked mode.
&NBSP
The structure of responsibility-attached mode
        The class diagram of the responsibility connection pattern is very simple, It consists of an abstract processing class and its set of implementation classes:
Abstract Processing class: An abstract processing class consists primarily of a member variable nexthandler of the next processing class and a method for processing the request handrequest,handrequest the main idea of the method is that If the processing conditions are met, then the processing class is handled by Nexthandler.
the specific processing class: the specific processing class is mainly to the specific processing logic and processing of the applicable conditions for implementation.
  instance

The responsibility chain model has two roles:
Abstract processor (Handler) role: defines a requested interface. If necessary, you can define a method for setting and returning a reference to a home object.
The specific processor (Concretehandler) role: If you can handle the request, if not handled, the request to the homes, let the deal. That is, it handles the requests it can handle and can access its own.
The test code for the above pattern is as follows:

Package chainofresp;
/**
 * Description: Abstract processing Role
 * * Public
abstract class Handler {

 protected Handler successor;
 /**
  * Description: Processing method * * Public
 abstract void handlerrequest (String condition);
 
 
 Public Handler Getsuccessor () {return
  successor;
 }
 public void Setsuccessor (Handler successor) {
  this.successor = successor;
 } 
 
}


Package chainofresp;
/**
 * Description: Specific processing role
 */Public
class ConcreteHandler1 extends Handler {

 @Override public
 Void Handlerrequest (String condition) {
  //If it is your own responsibility, deal with it yourself, be responsible for passing it to the homes if
  (condition.equals ("ConcreteHandler1")) {
   System.out.println ("ConcreteHandler1 handled");
   return;
  } else{
   System.out.println ("ConcreteHandler1 passed");
   Getsuccessor (). Handlerrequest (condition);
  }}}




Package chainofresp;
/**
 * Description: Specific processing role
 */Public
class ConcreteHandler2 extends Handler {
 
 @Override public
 Void Handlerrequest (String condition) {
  //If it is your own responsibility, deal with it yourself, be responsible for passing it to the homes if
  (condition.equals ("ConcreteHandler2")) {
   System.out.println ("ConcreteHandler2 handled");
   return;
  } else{
   System.out.println ("ConcreteHandler2 passed");
   Getsuccessor (). Handlerrequest (condition);
  }}}




Package chainofresp;
/**
 * Description: Specific processing role */public
class Concretehandlern extends Handler {

 /**
  * Here assume that n is the last node of the chain must be disposed
  of * In practice, a ring, or a tree, may appear,
  and this is not necessarily the last node.
  * */
 @Override public
 void Handlerrequest (String condition) {

  System.out.println (" Concretehandlern handled ");
  
 }

}


Package chainofresp;
/**
 * Description: Test class/Public
class Client {

 /**
  * Description:
  *
 /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 the responsibility of the ConcreteHandler2
  handler1.handlerrequest ("ConcreteHandler2");
  
  
 }



&NBSP
For example, in a toy factory production workshop, the assembly line is a chain of responsibility, if a toy aircraft has shell Assembly, engine assembly, propeller assembly, model Packer composition. When the object of the aircraft flow to who, who is responsible for the installation of this part of his responsibility, this part of the installation completed after the next link to know all the environment completed. This is a generated chain of responsibility. There is also a quality testing chain, quality testing also divided into multiple parts, shell detection, engine detection, propeller detection, packaging testing. When the product is left to the tester to detect the piece of their own, if there is a problem directly to carry out, if no problem is passed to the next inspector, until all the detection is completed. These are both chains of responsibility, but the difference is that each person who generates a responsibility chain processes and processes a part of the chain, and the quality inspection responsibility chains are judged, either disposed of or not dealt with. This is the responsibility chain of two categories, the latter is called pure responsibility chain, the former is called the impure responsibility chain, the pure responsibility chain in the actual application of very few, common for the impure responsibility chain, the model above is simulated pure responsibility chain to deal with.
 

the pros and cons of the responsibility chain Model
        responsibility chain mode and if...else ... He has a lower coupling, because it disperses the conditional judgment into the various processing classes, and the order of precedence of these processing classes can be set randomly. Responsibility chain model also has disadvantages, this with if...else ... The disadvantage of the statement is the same, that is, before finding the correct processing class, all the criteria must be executed again, when the responsibility chain is longer, the performance problem is more serious.
&NBSP
The applicable scenario for the responsibility chain mode
       as in the case of the beginning, if you use If...else ... Statement to organize a responsibility chain when the code looks bad, you can use the responsibility chain model to refactor.
 
Summary
       Responsibility chain mode is actually a flexible version of the If...else ... statement, which is to place the statements of these criteria in the various processing classes, the advantage of this is more flexible, but also bring risks, such as the setting of the processing of the relationship before and after, must be particularly careful, to deal with the logic of the conditions before and after the judgment of the relationship, and attention should not be in the chain of circular reference problems.

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.