C # design model (21) -- responsibility chain model

Source: Internet
Author: User
Tags class manager

C # design model (21) -- responsibility chain model
I. Introduction in real life, there are a lot of requests that are not answered by a single person. For example, if the salary for the interview is less than 10 thousand, the technical manager may decide, but 10 thousand ~ A salary of 10 thousand may not be approved by the Technical Manager and may need to be approved by the Technical Director. Therefore, after the interview, the interviewer often says, your salary I think you can use this technology, but you still need the approval of the technical director. This example also explains the content to be introduced in this article. This example in life really applies the responsibility chain model. II. Introduction to the responsibility chain model 2.1 the definition of the responsibility chain model can be found from examples in life that a request may require approval by several people, even if the technical manager has completed the approval, it still needs to be approved by a higher level. In this example, if you have asked for leave in the company for less than three days, the direct Leader can approve the request, and the project manager must approve the request within three days to seven days, the approval from the technical director is required for 7 days. I have introduced so many examples of the responsibility chain mode in life. The following describes the definition of the responsibility chain mode in object orientation. The responsibility chain mode means that a request must be processed by multiple objects to avoid coupling between request senders and receivers. Connect these objects to a chain and pass the request along the chain until an object processes it. 2.2 The structure of the responsibility chain model can be found from the definition of the responsibility chain model that the responsibility chain model involves only the processor role, but because there are multiple processors, they have common request processing methods, so here an abstract processor role is abstracted for code reuse. After this analysis, the structure of the responsibility chain model is self-evident. The specific structure is as follows. Two main roles are involved: the abstract Handler role (Handler): defines an interface for processing requests. This interface is usually implemented by an interface or abstract class. The specific handler role (ConcreteHandler): After receiving the request, the handler can choose to process the request or send the request to the next handler. Therefore, each specific handler needs to save the reference of the next handler to pass the request. 2.3 The Implementation of The responsibility chain model has been described above. The following uses the company's procurement as an example to implement the responsibility chain model. The company stipulates that the total price of the procurement architecture should be within 10 thousand and approved by managers. If the total price is greater than 10 thousand and less than 20 thousand, the vice president should approve the procurement architecture, if the total price is greater than 20 thousand, and the total price is less than 0.1 million, the approval of the general manager is required. If the total price is greater than 0.1 million, a meeting should be organized for discussion. For such a requirement, the most intuitive way is to design a method, the parameter is the total price of the purchase, and then adjust and judge the price in this method, then, different conditions are handed over to different levels of people for processing, which can solve the problem, but in this way, we need multiple if-else statements for judgment, however, when we add a new condition range, we have to modify the original design method to add another condition judgment. This design obviously violates the "open-closed" principle. At this time, the responsibility chain model can be used to solve such problems. The specific implementation code is as follows. Copy the code namespace ChainofResponsibility {// purchase request public class PurchaseRequest {// Amount public double Amount {get; set ;}// product name public string ProductName {get; set ;} public PurchaseRequest (double amount, string productName) {Amount = amount; ProductName = productName; }}// Approver, Handler public abstract class Approver {public Approver NextApprover {get; set ;} public string Name {get; set;} pub Lic Approver (string name) {this. name = name;} public abstract void ProcessRequest (PurchaseRequest request);} // ConcreteHandler public class Manager: Approver {public Manager (string name): base (name) {} public override void ProcessRequest (PurchaseRequest request) {if (request. amount <10000.0) {Console. writeLine ("{0}-{1} approved the request of purshing {2}", this, Name, request. productNa Me);} else if (NextApprover! = Null) {NextApprover. processRequest (request) ;}}// ConcreteHandler, Vice President public class VicePresident: Approver {public VicePresident (string name): base (name) {} public override void ProcessRequest (PurchaseRequest request) {if (request. amount <25000.0) {Console. writeLine ("{0}-{1} approved the request of purshing {2}", this, Name, request. productName);} else if (NextApprover! = Null) {NextApprover. processRequest (request) ;}}// ConcreteHandler, General Manager public class President: Approver {public President (string name): base (name) {} public override void ProcessRequest (PurchaseRequest request) {if (request. amount <100000.0) {Console. writeLine ("{0}-{1} approved the request of purshing {2}", this, Name, request. productName);} else {Console. writeLine ("Request requires a meeting to be organized for discussion") ;}} Class Program {static void Main (string [] args) {PurchaseRequest requestTelphone = new PurchaseRequest (4000.0, "Telphone"); PurchaseRequest requestSoftware = new PurchaseRequest (10000.0, "Visual Studio"); PurchaseRequest requestComputers = new PurchaseRequest (40000.0, "Computers"); Approver manager = new Manager ("LearningHard "); approver Vp = new VicePresident ("Tony"); Approver Pre = new President ("BossTom"); // sets the responsibility chain manager. nextApprover = Vp; Vp. nextApprover = Pre; // process the request manager. processRequest (requestTelphone); manager. processRequest (requestSoftware); manager. processRequest (requestComputers); Console. readLine () ;}} copies the code. Since the original design is not conducive to expansion due to changes in the scope of price conditions, according to the principle of "encapsulation change, at this point, we naturally want to be able to refine the price range to different classes? Because each price range determines an approver, multiple approval classes are created here, so that each class only needs to determine the price of its own range. This is the final implementation method of the responsibility chain. The specific running result is shown in. Iii. application scenarios of the responsibility chain model you can consider using the responsibility chain model in the following scenarios: if a system requires multiple objects for approval, for example, the leave system. If there are multiple if-else statements in the code, you can use the responsibility chain mode to refactor the code. Iv. Advantages and disadvantages of the mode: the advantages of the mode are self-evident. The main points are as follows: the coupling between request senders and receivers is reduced. Distribute multiple condition judgments to various processing classes to make the code clearer and the responsibility clearer. The responsibility chain model also has some disadvantages. For example, before finding the correct object to be processed, all condition judgments must be executed once. When the responsibility chain is too long, it may cause performance problems and may cause a request not to be processed.

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.