JAVA design pattern-responsibility chain mode (Chain of responsibility) __java

Source: Internet
Author: User
Tags exception handling

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: object behavior pattern

class Diagram:

        First look at a piece of code: [Java]   View plain copy 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 code's business logic is this way, with two parameters: the integer I and a request requests, depending on the value of I to decide who will handle the request, if i==1, handled by Handler1, if i==2, handled by Handler2, 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 several more troubling problems with this approach: code bloat: The decision conditions in the actual application are often 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 also written dead, if you want to change the order, then you can only modify this conditional statement.

Since the shortcomings we have already clear, we must find a way to solve. 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.

the structure of the responsibility-linked pattern

The class diagram of a liability-linked pattern is very simple, consisting of an abstract processing class and its set of implementation classes: Abstract handling Classes : the abstract processing class consists primarily of a member variable Nexthandler to the next processing class and a method for processing the request Handrequest, The main idea of handrequest method is that if the conditions of processing are met, the processing class is handled by Nexthandler. The concrete processing class: the concrete processing class mainly is realizes to the concrete processing logic and the processing application condition.

Once you understand the general idea of a liability-linked model, it's a good idea to look at the code:

Encapsulation Request Class request{}//Encapsulation response class response{}//abstract class abstract classes Handler {/** * Hold successor Responsibility Object * * Protect

	Ed Handler Next;

	/** * Signal processing of the request method, although this schematic method is not passed the parameters, but the actual can be passed in the parameters, according to the specific needs to choose whether to pass parameters/public abstract Response HandleRequest (Request req);
	/** * Value method/public Handler Getnexthandler () {return next;
	/** * Assign value method, set successor liability object/public void Setnexthandler (Handler next) {This.next = next;  }//Specific class Concretehandlera extends Handler {@Override public Response handlerequest (Request req) {/** * To determine whether there are successors, if any, to forward the request to the successor of responsibility if not, then process the request/if (Getnexthandler ()!= null) {SYSTEM.OUT.PRINTLN ("there is a successor responsibility chain object, do not deal with this time please Please...
			A ");
		Getnexthandler (). HandleRequest (req); else {System.out.println ("No successor responsibility chain object, handling this request ...")
		A ");
	return null; } class Concretehandlerb extends Handler {@Override public Response handlerequest (Request req) {if Getnexthandl ER ()!= null) {SYSTEM.OUT.PRINTLN ("there is a successor chain object that does not handle this request ...")
			B "); GetnexthAndler (). HandleRequest (req); else {System.out.println ("No successor responsibility chain object, handling this request ...")
		B ");
	return null; } class Concretehandlerc extends Handler {@Override public Response handlerequest (Request req) {if Getnexthandl ER ()!= null) {SYSTEM.OUT.PRINTLN ("there is a successor chain object that does not handle this request ...")
			C ");
		Getnexthandler (). HandleRequest (req); else {System.out.println ("No successor responsibility chain object, handling this request ...")
		C ");
	return null;  }///client calls public class Chainofresponsibilityclient {/** * @param args */public static void main (string[] args)
        {//Assemble responsibility chain Handler Handlera = new Concretehandlera ();
        Handler Handlerb = new Concretehandlerb ();
        
        Handler Handlerc = new Concretehandlerc ();
        Handlera.setnexthandler (Handlerb);
        
        Handlerb.setnexthandler (HANDLERC);
        Submit Request Req = new request ();
		
	Handlera.handlerequest (req); }
}


Run Result:

Have successor responsibility chain object, do not handle this request ... A
Have successor responsibility chain object, do not handle this request ... B
No successor responsibility chain object, processing this request ... C


The level class in the code is the simulation judgment condition, the request,response corresponds to the request and the response respectively, the abstract class handler mainly carries on the judgment of the condition, here simulates a processing level, only processing class's processing rank is higher than request's level can handle, Otherwise referred to the next processor to process. In the client class, set the chain in front and back to the execution of the relationship, the implementation of the request to the first processing class, which is the responsibility of the model, it completes the function and the previous if...else ... Statement is the same.


If you have seen the source code of Tomcat, you must have a vivid memory of the pipe mode (Pipeline) inside it; if you know the servlet specification, you will know the filter, and if you have used Struts2, you must be aware of the ubiquitous interceptor. The above concepts can be said to be the abstract of the pattern of responsibility chain, or variant.

the advantages and disadvantages of the responsibility chain model

Reduce the degree of coupling

This pattern makes it unnecessary for an object to know which other object is handling its request. Object only needs to know that the request will be handled "correctly". Neither the recipient nor the sender has a clear message, and the object in the chain does not need to know the structure of the chain. As a result, the chain of responsibility can simplify the mutual connection of objects. They only need to keep a reference to the successor, without having to keep all of its candidate recipients ' references.

Increased flexibility to assign responsibilities to objects (responsibility)

When assigning responsibilities in an object, the chain of responsibility gives you more flexibility. You can increase or change the responsibility for handling a request by dynamically adding or modifying the chain at run time. You can use this mechanism in conjunction with the inheritance mechanism of static exception handling objects.

Not guaranteed to be accepted

Since a request has no explicit recipient, there is no guarantee that it will be processed-the processing request may not be processed until the end of the chain.


the applicable scene of responsibility chain mode

There are multiple objects that can handle a request, and which object handles the request when the runtime is automatically determined. You want to submit a request to one of multiple objects in the case of an ambiguous recipient. The collection of objects that can handle a request should be dynamically specified.


Pure and impure responsibility chain model
 
A pure responsibility chain pattern requires a specific handler object to select only one of two behaviors: one is to assume responsibility, but to put responsibility to the next. A situation where a specific handler object is not allowed to pass the responsibility down after assuming part of the responsibility.
In a pure chain of responsibility, a request must be received by a handler object, and in an impure chain of responsibility, a request can end up not being received by any receiving end object.
The pure responsibility chain pattern's actual example is difficult to find, the general view example is the impure responsibility chain pattern realization. Some people think that the impure chain of responsibility is not a liability chain at all, which may make sense. But in the actual system, the pure chain of responsibility is hard to find. If the chain of responsibility is not pure is not a responsibility chain model, then the responsibility chain model will not have much meaning.


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.


Reference: http://blog.csdn.net/zhengzhb/article/details/7568676


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.