The responsibility chain pattern of Java design pattern

Source: Internet
Author: User

TAG: Structure operation ack Boolean send. com chain Assignment Example

The responsibility chain pattern of Java design pattern

The last few days to review the Java exception handling, contact with the responsibility chain mode. In an enterprise application, the request from the foreground throws an exception in the background, the design of exception handling usually uses the responsibility chain pattern, for example, SQL exception will not throw directly to the foreground, but after a series of processing and re-encapsulation, throw to the foreground a user identifiable exception information.

Brief introduction

The responsibility chain pattern is sometimes called the chain of responsibility pattern, which is a design pattern of object behavior. The purpose is to enable multiple objects to have the opportunity to process the request, thereby avoiding the coupling between the sender and receiver of the request, linking the objects into a chain, and passing the request along the chain until an object has processed it. The client sending the request does not know which object on the chain will handle the request, which allows the system to dynamically organize and assign responsibility without affecting the client.

It is important to note that the chain of responsibility can be a straight line, a chain of loops, or a part of a tree structure.

The filter in Tomcat is the use of the responsibility chain pattern.

Participants

Responsibility chain mode UML diagram:

A typical responsibility chain object graph might be this:

    • Handler: Abstract processor. Define an interface for processing requests, and if necessary, the interface can define a method to set and return a reference to the home. This role is typically implemented by a Java abstract class or Java interface. The aggregation relationship of the handler class gives a reference to the sub-class, and the abstract Method HandleRequest () regulates the operation of the sub-class processing request.
    • Concretehandler: Specific processor. After the specific processor accepts the request, it can choose to process the request immediately or pass the request to the other person. As the specific processor holds references to the homes, the specific processor can access the homes if necessary.
    • Client: Clients. Submits the request object to the processor.
code example

Requirements: department activities to the company to apply for funds, the amount of less than 1000 of the project manager can be approved, less than 2000 of the department manager can be approved, more than 2000 can only be approved by the general manager.

The responsibility chain pattern is used here. The applicant submits to the project manager to apply for funds, if the project manager has sufficient authority to approve, if not enough, submits to the superior leader, and so on, until the request can be processed.

Code implementation:

Handler: Abstract parent class for approving staff

package com.wangjun.designPattern.chainOfResponsibility;publicabstractclass Handler {    protected Handler successor;        publicabstractbooleanhandler(int fee);        publicabstractvoidsetSuccessor(Handler successor);        publicabstractgetSuccessot();}

ConcreteHandler1: Project Manager

Package com.wangjun.designPattern.chainOfResponsibility; Public classProjectmanagerextendsHandler {@Override     Public Boolean Handler(intFee) {if(Fee <= +) {System. out.println("project manager: Approval approved." Amount: "+ fee);return true; }Else{System. out.println("The amount is greater than 1000, the project manager is not authorized to approve, transfer to department manager!" ");Setsuccessor(New Departmentmanager());returnSuccessor.Handler(fee); }    }@Override     Public void Setsuccessor(Handler successor) { This.successor= successor; }@Override     PublicHandlerGetsuccessot() {returnsuccessor; }}

ConcreteHandler2: Department Manager

Package com.wangjun.designPattern.chainOfResponsibility; Public classDepartmentmanagerextendsHandler {@Override     Public Boolean Handler(intFee) {if(Fee <= -) {System. out.println("department Manager: approval approved." Amount: "+ fee);return true; }Else{System. out.println("The amount is more than 2000, the department manager is not authorized to approve, handing over to general manager!" ");Setsuccessor(New Manager());returnSuccessor.Handler(fee); }    }@Override     Public void Setsuccessor(Handler successor) { This.successor= successor; }@Override     PublicHandlerGetsuccessot() {returnsuccessor; }}

ConcreteHandler3: General Manager

Package com.wangjun.designPattern.chainOfResponsibility; Public classManagerextendsHandler {@Override     Public Boolean Handler(intFee) {if(Fee <=10000) {System. out.println("General Manager: Approval approved." Amount: "+ fee);return true; }Else{System. out.println("The amount is greater than 10000, approval does not pass!" Application Amount: "+ fee);return false; }    }@Override     Public void Setsuccessor(Handler successor) { This.successor= successor; }@Override     PublicHandlerGetsuccessot() {returnsuccessor; }}

Client: Customer application fee

Package com.wangjun.designPattern.chainOfResponsibility; Public classClient { Public Static void Main(string[] args) {//Test request fee List        int[] arr = { -, the,2500,29000};//Project Manager to submit the applicationProjectmanager pm =New Projectmanager(); for(inti =0; I < arr.length; i++) {System. out.println("section"+ (i+1) +"Fee");if(PM.Handler(Arr[i])) {System. out.println("Successful application of funds!" "); }Else{System. out.Print("The application for funding failed!" "); } System. out.println(); }    }}

Operation Result:

第1笔费用项目经理:审批通过。金额:500申请经费成功!第2笔费用金额大于1000,项目经理无权审批,移交给部门经理!部门经理:审批通过。金额:1500申请经费成功!第3笔费用金额大于1000,项目经理无权审批,移交给部门经理!金额大于2000,部门经理无权审批,移交给总经理!总经理:审批通过。金额:2500申请经费成功!第4笔费用金额大于1000,项目经理无权审批,移交给部门经理!金额大于2000,部门经理无权审批,移交给总经理!金额大于10000,审批不通过!申请金额:29000申请经费失败!
Summarize

You can use the responsibility chain mode under the circumstances:

    • There are multiple objects that can handle the same request and which object processing requests are determined automatically at run time;
    • You want to submit a request to multiple objects without explicitly specifying the recipient;
    • A collection of objects that can handle a request should be specified dynamically.

Pure and impure chain of Duty mode

A pure chain of responsibility requires a specific handler object to choose only one of two behaviors: one is to take responsibility, but to push the responsibility to the next. 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 received by a handler object, and in an impure chain of responsibility, a request can eventually not be received by any of the receiving end objects.

The actual example of the pure responsibility chain model is difficult to find, and the examples we see are the implementation of the impure responsibility chain model. Some people think that the impure chain of responsibility is not the responsibility chain at all, which may make sense. But in a real system, a pure chain of responsibility is hard to find. If the adherence to the chain of responsibility is not the responsibility chain model, then the chain of responsibility model will not have much significance.

Loading ...

Follow up on Tomcat's filter mechanism.

Reference:

"Design Mode"

7702368

The responsibility chain pattern of Java design pattern

Related Article

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.