Java Design Pattern Learning record-responsibility chain model

Source: Internet
Author: User
Objective

has already introduced five creation design pattern and seven structure type design pattern to finish, from this beginning to introduce the behavior pattern design pattern, the first to introduce the behavior type design pattern is the responsibility chain pattern (also called the responsibility chain pattern).

Introduction to the concept of responsibility chain model

The responsibility chain pattern is to avoid coupling between the sender and receiver of the request, so that multiple receiving objects have the opportunity to process the request. Practice these objects as a chain and pass the request along the chain until an object handles it . It is also possible that there are no objects in the chain of responsibility that can handle the request, which is allowed.

Example

Or the previous law, first cite specific code examples, and then analyze. Take before the son in my old club happened one thing, colleague Xiao Wang to get married, so want to leave home to prepare for the wedding, but the company has a clear rules and regulations, leave need to apply in advance, and each level of leadership can approve the holiday days are not the same, department manager can approve 1 to 2 days of vacation, the technical director can approve 3-5 days of vacation, more than 5 days to find the CEO approval, if the CEO approved by the time to rest more than 5 days of vacation, Xiao Wang preparation for the wedding and honeymoon in total to please 10 working days of vacation.

Using code to implement this process is the way it looks.

Create a leave bar class first

/*** Leave section*/@Data @allargsconstructor Public classLeave {/*Department*/    PrivateString Department; /*Employee Name*/    PrivateString name; /*Days of Leave*/    Private DoubleDays ; /*reasons for Leave*/    PrivateString cause;}

Then create an abstract class for approvers

/*** Approving person*/ Public Abstract classApprover {/*Approver Name*/String name; /*next approver.*/approver Nextapprover;  Publicapprover (String name) { This. Name =name; }    /*** Set up next approver *@paramApprover*/     Public voidSetnextapprover (Approver approver) { This. Nextapprover =approver; }    /*** Approval *@paramLeave*/     Public Abstract voidapproval (Leave Leave);}

Department Manager

/*** Department Manager*/ Public classManagerextendsApprover {/*** Set name *@paramName leader*/     PublicManager (String name) {Super(name); }    /*** Approval *@paramLeave leave section*/@Override Public voidapproval (Leave Leave) {if(Leave.getdays () <3) {System.out.println ("Leave less than 3 days, calculate a temporary rest, approved." "); System.out.println (The department manager approves the---------approval process over. "); }Else{            if(Objects.nonnull (nextapprover)) {System.out.println ("The department manager can not approve so many days of vacation, need superior approval." ");  This. Nextapprover.approval (leave); }Else{System.out.println (name+ "The leader is not there, wait." "); }        }    }}

Technical Director

/*** Technical Director*/ Public classTechnicaldirectorextendsApprover {/*** Set name *@paramName leader*/     Publictechnicaldirector (String name) {Super(name); }    /*** Approval *@paramLeave leave section*/@Override Public voidapproval (Leave Leave) {if(Leave.getdays () <5) {System.out.println ("Leave less than 5 days, calculate something to rest, approved." "); System.out.println ("Technical director approves---------approval process over. "); }Else{            if(Objects.nonnull (nextapprover)) {System.out.println ("The technical director can not approve so many days of vacation, need superior approval." ");  This. Nextapprover.approval (leave); }Else{System.out.println (name+ "The leader is not there, wait." "); }        }    }}

Ceo

/*** CEO*/ Public classCeoextendsApprover {/*** Set name *@paramName leader*/     PublicCEO (String name) {Super(name); }    /*** Approval *@paramLeave leave section*/@Override Public voidapproval (Leave Leave) {if(Leave.getdays () >5&&leave.getdays () <=10) {System.out.println ("The situation was special, approved." "); System.out.println ("CEO approval through---------approval process over. "); }Else{System.out.println (name+ "say the time for leave is too long not to batch, it is best not to take so long." "); }    }}

Test class

 Public classClient { Public Static voidMain (string[] args) {//write a leave slipLeave Leave =NewLeave ("Technical department", "Xiao Wang", 6.0, "marriage"); //Create an approval nodeApprover Zhangge =NewManager ("Brother Zhang"); Approver Laozhao=NewTechnicaldirector ("Lao Zhao")); Approver Lizong=NewCEO ("Li General"); //string up the approval nodeZhangge.setnextapprover (Laozhao);        Laozhao.setnextapprover (Lizong); //Start Approvalzhangge.approval (leave); }}

Run results

department manager can not approve so many days of vacation, need superior approval. Technical director can not approve so many days of vacation, need superior approval. The situation was special and approved. The CEO approves the---------approval process over.

By running the results, we can see that when the number of days to leave is 10 days, the department manager and the technical director have not been able to handle, and then cast to the CEO, through the CEO special approval Xiao Wang's marriage leave request to forget the approval is completed. This example uses the responsibility chain model we are talking about today and continues to analyze the responsibility chain model.

The structure diagram of responsibility chain of responsibility chain model analysis

The main roles involved

Abstract Processor (Handler) role : An abstract processor is used to define an interface for processing requests, and if necessary, the interface can define a method to return a reference to the next processing object. The approver in the above example is the representative of this role.

specific Processor (Concretehandler) role : Process the request that is received, you can choose to dispose of the request, or pass the request to the other person. The manager and Technicaldirector as well as the CEO in the example above represent this role.

The responsibility chain model summarizes the pure responsibility chain model and the impure responsibility chain pattern
    • The pure chain of responsibility model requires a specific processor object to choose only one of two behaviors: one is to take responsibility, and the other is to put the blame on the next person. A situation in which a specific processor object is not allowed to transmit responsibility after taking part of the responsibility. In a pure chain of responsibility, a request must be accepted by one of the handler objects.
    • The impure chain of responsibility allows a request to be partially processed by a specific processor and then passed down, or a specific processor can continue to process the request after processing a request, and a request can eventually not be received by any processor object. For example, event bubbling in JavaScript.
The advantages of the responsibility chain model

1, the request does not need to indicate which object is processed, this effect is the decoupling between the requester and the receiver, and the object in the chain does not need to clear the structure of other chains, but also reduces the coupling.

2. The request processing object only needs to maintain a reference to the subsequent successor, and does not need to maintain all the processing objects, simplifying the mutual connection between the objects.

3, in assigning responsibilities to the object, the chain of responsibility can give us more flexibility, you can increase or change the responsibility of processing a request by dynamically adding or modifying the chain at runtime.

4, add a request processing object, do not need to change the existing code, only need to reset the connection, in line with the "open and close principle."

Disadvantages of the responsibility chain model

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

2, for a longer chain of responsibility, the processing of requests may involve multiple processing objects, not only increase the complexity of the code and system performance will also be affected, and the code debugging is not very convenient.

3, Jo Jian chain improper, may cause circular call, will lead to the system into a dead loop.

Applicable scenarios

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

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

3, can dynamically specify a set of object processing requests, the client can dynamically create a responsibility chain to handle requests, but also can change the order of the handlers in the chain.

In fact, in our daily development there will also be applicable to the responsibility chain model of the scene, Try/catch, servlet (each Servelt call), and filter, etc.

To learn more about design patterns, see the Java Design Patterns Learning record-gof design pattern Overview.

Is the industry depressed now? How come you've had fewer interview opportunities lately?

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.