Chain of Responsibility Pattern, food chain

Source: Internet
Author: User
Tags define abstract

Chain of Responsibility Pattern, food chain

Finally, CSDN was chosen to sort out the knowledge points published over the past few years. This article was migrated to CSDN in parallel. Because CSDN also supports the MarkDown syntax, it's awesome!

[Craftsman if water http://blog.csdn.net/yanbober] read the previous article "State Pattern" http://blog.csdn.net/yanbober/article/details/45502665

Overview

A responsibility chain can be a straight line, a ring, or a tree structure. The most common responsibility chain is a straight line, that is, requests are transmitted along a one-way chain. Each object in the chain is a request handler. In the responsibility chain mode, the request handler can be organized into a chain and the request is transmitted along the chain, the handler on the chain processes the request accordingly. The client only needs to send the request to the chain without worrying about the request processing details and transmission of the request. This decouples the request sender and the request handler.

Core

Concept:To avoid coupling between request senders and receivers, multiple objects may receive requests, connect these objects into a chain, and pass requests along the chain, until an object processes it. The responsibility chain mode is an object behavior mode.

Important core modules of the responsibility chain model structure:

Handler)

Define an interface for processing requests. It is generally designed as an abstract class. Because different handlers process requests in different ways, they define abstract request processing methods. Because each processor is still a processor, the abstract processor defines an object of the abstract Processor type as its reference to the next processor. With this reference, the processor can join a chain. (Is it a bit like the linked list structure in C ?)

ConcreteHandler (Specific handler)

The subclass of the abstract processor can process user requests. In the specific handler class, the abstract request processing method defined by the abstract processor is implemented. It must be judged before processing the request, check whether the request has the corresponding processing permission. If the request can be processed, it will be processed; otherwise, the request will be forwarded to the successor; in the specific handler, the next object in the chain can be accessed for request forwarding.

Classification of responsibility chain modes:

Pure responsibility chain model

A pure responsibility chain model requires that a specific processor can only select one of the two actions: either take full responsibility or push the responsibility to the next house, it is not allowed that a specific processor object passes down its responsibilities after assuming part or all of its responsibilities. In the pure responsibility chain mode, a request must be received by a handler object and cannot be processed by any handler object.

Non-pure responsibility chain model

In a non-pure responsibility chain model, a request is allowed to be processed by a specific processor before being passed down. Or after a specific processor processes a request, its successor can continue to process the request, in addition, a request cannot be received by any handler object. The event processing model in Java AWT 1.0 applies the non-pure responsibility chain model (in fact, the Android event distribution mechanism is similar). Its basic principles are as follows: because the window components (such as buttons and text boxes) are generally located in the container components, when an event occurs on a component, the handleEvent () of the component object is used first () the method passes the event to the corresponding event processing method. The event processing method processes the event and determines whether to send the event to the container component of the upper level; after receiving the event, the upper-level container component can continue to process the event and decide whether to continue to spread the event to the upper-level container component until the event reaches the upper-level container component; if no processing method is available until it is uploaded to the top-level container, the event will not be processed. When an event is received by each level-1 component, the event can be handled, regardless of whether the event has been processed at the upper level. Obviously, this is a pure responsibility chain model. This Event processing mechanism in the early Java AWT Event model (JDK 1.0 and earlier) is also called the Event Bubbling mechanism. After Java.1.1, JDK uses the observer mode instead of the responsibility chain mode to process events. Currently, this event floating mechanism can still be used in JavaScript For event processing.

Use Cases

Multiple objects can process the same request. The client only needs to submit the request to the chain, you do not need to worry about who the request is to be processed and how it is processed.

If the recipient is not explicitly specified, a request is submitted to one of multiple objects.

A group of objects can be dynamically specified to process requests. The client can dynamically create a responsibility chain to process requests and change the order of the handlers in the chain.

Program ape instance

Here is an example of the responsibility chain model (simulating the Android App development process, programmers need to find the UI Designer to review the UI effect, find the Leader review code, and find the test engineer to test the App, then ask the product manager to confirm the App and publish the App), strictly abide by the core templates of the responsibility chain model, not to mention:

Package yanbober. github. io; // constant interface Type {int UI_EFFECT = 0; int CODE_FORMAT = 1; int TEST_PROJECT = 2; int PUBLISH_APP = 3;} // Handler (Abstract Handler) abstract class Handler {private Handler mHandler; public Handler getmHandler () {return mHandler;} public void setmHandler (Handler mHandler) {this. mHandler = mHandler;} abstract String handleRequest (int type, String user);} // ConcreteHandler (Specific handler) fig Ss ConcreteHandlerGUI extends Handler {@ Override String handleRequest (int type, 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) ;}} return ret ;}} class ConcreteHandlerTeamLeader extends Handler {@ Override String handleRequest (int type, 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) ;}} return ret ;}} class ConcreteHandlerPM extends Handler {@ Override String handleRequest (int type, 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) ;}} return ret ;}} class ConcreteHandlerTestEngineer extends Handler {@ Override String handleRequest (int type, 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) ;}} return ret ;}// client public class Main {public static void main (String [] args) {Handler code = new ConcreteHandlerTeamLeader (); handler ui = new ConcreteHandlerGUI (); Handler test = new ConcreteHandlerTestEngineer (); Handler publish = new ConcreteHandlerPM (); code. setmHandler (ui); ui. setmHandler (test); test. setmHandler (publish); // yanbo finds the team leader review code System. out. println (code. handleRequest (Type. CODE_FORMAT, "YanBo"); // find the team leader test code System. out. println (code. handleRequest (Type. TEST_PROJECT, "YanBo "));}}
Summary

Advantages of the responsibility chain model:

The responsibility chain mode makes it unnecessary for an object to know which object is processing its request. The object only needs to know that the request will be processed. The recipient and the sender do not have the explicit information of the other party, the objects in the chain do not need to know the structure of the chain. The client is responsible for the creation of the chain, reducing the Coupling Degree of the system.

The request processing object only needs to maintain a reference pointing to its successor, and does not need to maintain its reference to all candidate handlers, which simplifies the interconnection of objects.

When assigning responsibilities to objects, the responsibility chain can give us more flexibility, you can dynamically add or modify the chain at runtime to add or change the responsibility for processing a request.

When a new specific request handler is added to the system, you do not need to modify the code of the original system. You only need to re-create the chain on the client. From this point of view, it is in line with the "open and closed principle.

Disadvantages of the responsibility chain model:

Because a request does not have a clear receiver, it cannot be guaranteed that it will be processed, and the request may not be processed until the end of the chain; A request may not be processed because the responsibility chain is not correctly configured.

For a long responsibility chain, request processing may involve multiple processing objects, and the system performance will be affected, and it is not convenient for code debugging.

If the chain is improperly built, it may cause loop calls, which will lead to an endless loop of the system.

[Craftsman if water http://blog.csdn.net/yanbober] continue to read the design Pattern (behavior-oriented) Mediator Pattern http://blog.csdn.net/yanbober/article/details/45533335

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.