Model of responsibility Chain (Chain of Responsibility pattern) in design mode (behavioral type)

Source: Internet
Author: User

PS One sentence: Eventually choose Csdn to organize the publication of the knowledge points of these years, the article parallel migration to CSDN. Because CSDN also support markdown grammar, Ah!

"Craftsman Joshui Http://blog.csdn.net/yanbober" read the previous article "mode of Design (behavioral) state pattern" http://blog.csdn.net/yanbober/article/ details/45502665

Overview

A chain of responsibility can be a straight line, a ring, or a tree structure, and the most common chain of responsibilities is a straight line, which is to pass a request along a one-way chain. Each object on the chain is a request handler, and the responsibility chain pattern organizes the requested processor into a chain and allows the request to be passed along the chain, which is handled by the processor on the chain, and the client does not care about the processing details of the request and the delivery of the request, simply sending the request to the chain. Implements the decoupling of the request sender and the request processor.

Core

Concept: avoid the request sender to be coupled with the receiver, so that multiple objects may receive the request, connect the objects as a chain, and pass the request along the chain until there is an object to handle it. The responsibility chain pattern is an object-based behavioral pattern.

Responsibility chain model structure important core module:

Handler (abstract processor)

Defines an interface for processing requests, typically designed as abstract classes, in which the abstract request processing method is defined because different specific handlers handle the request differently. Because each processor's next-of-the-box is a handler, an object of the abstract processor type is defined in the abstract processor as its reference to the next. With this reference, the processor can be linked into a chain. (Is it a bit like the C-language linked list structure?) )

Concretehandler (Specific processor)

The subclass of the abstract processor, which can handle user requests, implements abstract request handling methods defined in the abstract processor in the specific processor class, needs to be judged before processing the request, to see if there is a corresponding processing privilege, and if the request can be processed, the request is forwarded to the successor In a specific processor, the next object in the chain can be accessed for the requested forwarding.

Responsibility chain Pattern Classification:

Pure chain of responsibility model

A purely chain of responsibility pattern requires a specific processor object to choose only one of two behaviors: either take full responsibility, or push the responsibility to the next place, and not allow a particular processor object to pass down the responsibility after assuming part or all of the responsibility. And in a pure chain of Duty mode, a request must be received by a handler object, and a request cannot be handled by any one of the handler objects.

The impure responsibility chain model

In an impure chain of duty mode, a request is allowed to be partially processed by a specific processor and then passed down, or a specific processor can continue to process the request after it has been processed, and a request can eventually not be received by any processor object. The event-handling model in Java AWT 1.0 applies an impure responsibility chain pattern (in fact, the Android event distribution mechanism is similar) with the following rationale: Because window components, such as buttons, text boxes, and so on, are generally located in container components, when an event occurs on a component, The event is passed to the appropriate event-handling method by the Handleevent () method of the Component object, which handles the event and then decides whether to propagate the event up to the first-level container component The parent container component can continue to handle this event after receiving the event and decide whether to continue propagating to the parent container component, so repeatedly, until the event reaches the top container component, and if the top-level container is still not processed, the event is not processed. Each level of a component can handle this event when it receives an event, regardless of whether the event has been processed at the previous level, and if the event has not been processed. Obviously, this is an impure responsibility chain pattern, and this event-handling mechanism in the early Java AWT Event model (JDK 1.0 and earlier) is called the event bubbling mechanism. From java.1.1 onwards, the JDK uses the observer pattern instead of the responsibility chain pattern to handle events. Currently, this event float mechanism can still be used in JavaScript for event handling.

Usage Scenarios

There are multiple objects that can handle the same request, and which object handles the request at a time when it is determined that the client simply commits the request to the chain without needing to care who the requested processing object is and how it is handled.

Submits a request to one of several objects without explicitly specifying the recipient.

A set of object processing requests can be dynamically specified, and the client can dynamically create a chain of responsibilities to process requests and change the order of the handlers in the chain.

Program Ape Instance

Here is an example of a chain of responsibility model (simulating the Android app development process, the program ape writing code needs to look for UI designer to review UI effects, find leader review code, find a test engineer to test the app, then go to the Product manager to confirm the app Post app), Strict adherence to the responsibility chain model several core templates, not many explanations:

 PackageYanbober.github.io;//ConstantsInterface Type {intUi_effect =0;intCode_format =1;intTest_project =2;intPublish_app =3;}//handler (abstract processor)AbstractClass Handler {PrivateHandler Mhandler; PublicHandlerGetmhandler() {returnMhandler; } Public void Setmhandler(Handler Mhandler) { This. Mhandler = Mhandler; }AbstractString HandleRequest (intType, String user);}//concretehandler (Specific processor)Class Concretehandlergui extends Handler {@OverrideString HandleRequest (intType, string user) {string ret ="";if(Type.ui_effect = = Type) {ret = user +"' s App UI is ok!"; }Else{if(Getmhandler ()! =NULL) {System.out.println ("*********** Concretehandlergui **************");            ret = Getmhandler (). HandleRequest (type, user); }        }returnRet }}class Concretehandlerteamleader extends Handler {@OverrideString HandleRequest (intType, string user) {string ret ="";if(Type.code_format = = Type) {ret = user +"' s APP code format is ok!"; }Else{if(Getmhandler ()! =NULL) {System.out.println ("*********** concretehandlerteamleader **************");            ret = Getmhandler (). HandleRequest (type, user); }        }returnRet }}class concretehandlerpm extends Handler {@OverrideString HandleRequest (intType, string user) {string ret ="";if(Type.publish_app = = Type) {ret = user +"' s App can be publish!"; }Else{if(Getmhandler ()! =NULL) {System.out.println ("*********** concretehandlerpm **************");            ret = Getmhandler (). HandleRequest (type, user); }        }returnRet }}class Concretehandlertestengineer extends Handler {@OverrideString HandleRequest (intType, string user) {string ret ="";if(Type.test_project = = Type) {ret = user +"' s App test is ok!"; }Else{if(Getmhandler ()! =NULL) {System.out.println ("*********** concretehandlertestengineer **************");            ret = Getmhandler (). HandleRequest (type, user); }        }returnRet }}//Client Public  class Main {     Public Static void Main(string[] args) {Handler Code =NewConcretehandlerteamleader (); Handler UI =NewConcretehandlergui (); Handler test =NewConcretehandlertestengineer (); Handler publish =NewCONCRETEHANDLERPM ();        Code.setmhandler (UI);        Ui.setmhandler (test); Test.setmhandler (publish);//yanbo Find team leader review codeSystem.out.println (Code.handlerequest (Type.code_format,"Yanbo"));//yanbo Find team leader test codeSystem.out.println (Code.handlerequest (Type.test_project,"Yanbo")); }}
sum up a

Responsibility Chain Model Advantages:

The responsibility chain mode makes an object need not know which object to handle its request, the object only needs to know that the request will be processed, the receiver and sender have no explicit information, and the object in the chain does not need to know the structure of the chain, the client is responsible for the creation of the chain, reducing the system coupling degree.

The request processing object only needs to maintain a reference to the subsequent successor, without maintaining its reference to all the candidate handlers, simplifying the object's connection to each other.

When assigning responsibilities to an object, the chain of responsibility gives us more flexibility to increase or change the responsibility for handling a request by dynamically adding or modifying the chain at run time.

In the system to add a new specific request processor without modifying the original system code, only need to re-build the chain on the client, from this point of view is in line with the "open and closed principle."

Responsibility Chain Model Disadvantages:

Because a request does not have a clear recipient, there is no guarantee that it will be processed, that the request may not be processed until the end of the chain, and that a request may not be processed because the responsibility chain is not properly configured.

For a longer chain of responsibilities, the processing of the request may involve multiple processing objects, and system performance will be affected, and it is inconvenient to debug the code.

If the chain is improperly built, it can cause circular calls, which will cause the system to fall into a dead loop.

"Craftsman Joshui Http://blog.csdn.net/yanbober" Continue reading "to be continued ... 》

Model of responsibility Chain (Chain of Responsibility pattern) in design mode (behavioral type)

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.