当前位置:网站首页>14 responsibility chain mode

14 responsibility chain mode

2022-06-22 08:29:00 Grow some hair.

Reprint of the original :https://blog.csdn.net/sinat_21107433/article/details/102790445

In response to the needs of the project , The company arranged Jungle Go to Chengdu on business for a period of time . see ,Jungle Just finished my business trip , Return to the company for reimbursement . Forget it ,Jungle There are about 50 A small amount of bills of million need to be reimbursed . According to the company's regulations ,Jungle You have to find your team leader to sign first .

Team leader, take a look ,“ Tut tut tut , I can only deal with 10 Reimbursement of less than 10000 yuan , I'll sign your list , You have to find brother Bing ( executive director ) Sign ”, therefore Jungle And ran to find brother Bing .

Brother Bing looked ,“ Tut tut tut , The maximum amount I can manage is no more than 30 Wan's list , You have to find Mr. Chun ( The manager ) Sign ”.Jungle And took great pains to find president Chun .

Spring always looks ,“ o ,50 ten thousand , A lot ! but 60 I can control everything below ten thousand , I signed this list for you ! If it exceeds 60 ten thousand , You dog have to go to the boss !”Jungle I'm relieved at last , Find leaders on the Internet , It's not easy !

In the unit , Each leader has different approval authority , Reimbursement documents with different amounts are submitted layer by layer , Finally, it is in the hands of the leader who has the right to deal with the amount range , The approval of this form is completed . This is a Jungle company ( I believe most of the companies ) The system of . If you want to use code to simulate this system , Is there a model to refer to ?

The answer is : Yes ! That is the responsibility chain model ! 

1. A brief introduction to the responsibility chain model

Responsibility chain mode is also called responsibility chain mode . In many cases , There may be more than one object that can handle a request , The request can be passed from the lower house to the upper house level by level along the relationship formed between certain objects , Form a chain —— Responsibility chain . The responsibility chain can be a straight line , It can also be a ring or tree structure . The common form of responsibility chain is straight line . Every object in the chain is the handler of the request , All the client has to do is send the request , You don't need to care about the processing details of the request . thus , The responsibility chain pattern decouples the requester from the receiver of the request .

The responsibility chain pattern is defined as follows :

Responsibility chain pattern :

Avoid coupling the sender and receiver of a request , Let multiple objects have the opportunity to process requests . Connect the objects receiving the request into a chain , And pass the request along the chain , Until an object can handle it .

2. Responsibility chain model structure

Responsibility chain model UML The structure is shown in the following figure , The core of the responsibility chain pattern is the introduction of an abstract handler :

There are two roles in the responsibility chain pattern :

  • Handler( Abstract processor ): Abstract handlers are generally abstract classes , Declares an interface for processing requests handleRequest(), Defines an object of abstract handler type , As a reference to his family , Through this reference, a chain of responsibility can be formed .
  • ConcreteHandler( Specific handler ): Is a subclass of the abstract handler , Implements the interface for processing requests . In the concrete realization , If the specific handler can handle the request , Just deal with it , Otherwise, forward the request to the successor . The specific handler can access the next object .

As can be seen from the above , In the responsibility chain model, many objects are connected by each object's reference to its next home to form a chain , Requests are passed level by level on this chain , Until a certain level can handle the request . The client does not know and does not have to know which level of processor handled the request , Because every handler has the same interface handleRequest(). Next, we will further understand the responsibility chain model through an example .

3. Responsibility chain pattern code example

Take the example in the introduction , For bills of different amounts , The handling of leaders at different levels of the company is as follows :

amount of money 0~10 ten thousand : The team leader can handle

amount of money 10~30 ten thousand : The supervisor handles

amount of money 30~60 ten thousand : The manager handles

The amount exceeds 60 ten thousand : The boss handles

In this section, Jungle Will use C++ Simulate the process . This example UML The graph is as follows :

3.1. Notes

 
  1. // request : Notes

  2. class Bill

  3. {

  4. public:

  5. Bill(){}

  6. Bill(int iId, string iName, double iAccount){

  7. id = iId;

  8. name = iName;

  9. account = iAccount;

  10. }

  11. double getAccount(){

  12. return this->account;

  13. }

  14. void print(){

  15. printf("\nID:\t%d\n", id);

  16. printf("Name:\t%s\n", name.c_str());

  17. printf("Account:\t%f\n", account);

  18. }

  19. private:

  20. int id;

  21. string name;

  22. double account;

  23. };

3.2. Abstract processor

 
  1. // Abstract processor

  2. class Approver

  3. {

  4. public:

  5. Approver(){}

  6. Approver(string iName){

  7. setName(iName);

  8. }

  9. // Add superior

  10. void setSuperior(Approver *iSuperior){

  11. this->superior = iSuperior;

  12. }

  13. // Processing requests

  14. virtual void handleRequest(Bill*) = 0;

  15. string getName(){

  16. return name;

  17. }

  18. void setName(string iName){

  19. name = iName;

  20. }

  21. protected:

  22. Approver *superior;

  23. private:

  24. string name;

  25. };

3.3. Specific handler

3.3.1. Specific handler : group leader

 
  1. // Specific handler : group leader

  2. class GroupLeader :public Approver

  3. {

  4. public:

  5. GroupLeader(){}

  6. GroupLeader(string iName){

  7. setName(iName);

  8. }

  9. // Processing requests

  10. void handleRequest(Bill *bill){

  11. if (bill->getAccount() < 10){

  12. printf(" group leader %s The bill was processed , Note information :",this->getName().c_str());

  13. bill->print();

  14. }

  15. else{

  16. printf(" The team leader has no right to deal with , Transfer to superior ……\n");

  17. this->superior->handleRequest(bill);

  18. }

  19. }

  20. };

3.3.2. Specific handler : executive director

 
  1. // Specific handler : executive director

  2. class Head :public Approver

  3. {

  4. public:

  5. Head(){}

  6. Head(string iName){

  7. setName(iName);

  8. }

  9. // Processing requests

  10. void handleRequest(Bill *bill){

  11. if (bill->getAccount() >= 10 && bill->getAccount()<30){

  12. printf(" executive director %s The bill was processed , Note information :", this->getName().c_str());

  13. bill->print();

  14. }

  15. else{

  16. printf(" The supervisor has no authority to deal with , Transfer to superior ……\n");

  17. this->superior->handleRequest(bill);

  18. }

  19. }

  20. };

3.3.3. Specific handler : The manager

 
  1. // Specific handler : The manager

  2. class Manager :public Approver

  3. {

  4. public:

  5. Manager(){}

  6. Manager(string iName){

  7. setName(iName);

  8. }

  9. // Processing requests

  10. void handleRequest(Bill *bill){

  11. if (bill->getAccount() >= 30 && bill->getAccount()<60){

  12. printf(" The manager %s The bill was processed , Note information :", this->getName().c_str());

  13. bill->print();

  14. }

  15. else{

  16. printf(" The manager has no authority to deal with , Transfer to superior ……\n");

  17. this->superior->handleRequest(bill);

  18. }

  19. }

  20. };

3.3.4. Specific handler : Boss

 
  1. // Specific handler : Boss

  2. class Boss :public Approver

  3. {

  4. public:

  5. Boss(){}

  6. Boss(string iName){

  7. setName(iName);

  8. }

  9. // Processing requests

  10. void handleRequest(Bill *bill){

  11. printf(" Boss %s The bill was processed , Note information :", this->getName().c_str());

  12. bill->print();

  13. }

  14. };

3.5. Client code example

The client creates four roles , They are the team leaders 、 executive director 、 Manager and boss , And set up a superior subordinate relationship . And then created 4 Bills , The amount varies , All of them will be handed over to the team leader for handling .

 
  1. #include <iostream>

  2. #include "ChainOfResponsibility.h"

  3.  
  4. int main()

  5. {

  6. // Request handler : group leader , Brother Bing , Chunzong , Boss

  7. Approver *zuzhang, *bingge, *chunzong, *laoban;

  8.  
  9. zuzhang = new GroupLeader(" Brother sun ");

  10. bingge = new Head(" Brother Bing ");

  11. chunzong = new Manager(" Chunzong ");

  12. laoban = new Boss(" Boss Zhang ");

  13.  
  14. zuzhang->setSuperior(bingge);

  15. bingge->setSuperior(chunzong);

  16. chunzong->setSuperior(laoban);

  17.  
  18. // Create a reimbursement form

  19. Bill *bill1 = new Bill(1, "Jungle", 8);

  20. Bill *bill2 = new Bill(2, "Lucy", 14.4);

  21. Bill *bill3 = new Bill(3, "Jack", 32.9);

  22. Bill *bill4 = new Bill(4, "Tom", 89);

  23.  
  24. // All shall be submitted to the team leader for approval

  25. zuzhang->handleRequest(bill1); printf("\n");

  26. zuzhang->handleRequest(bill2); printf("\n");

  27. zuzhang->handleRequest(bill3); printf("\n");

  28. zuzhang->handleRequest(bill4);

  29.  
  30. printf("\n\n");

  31. system("pause");

  32. return 0;

  33. }

3.6. effect

The operation results are as follows , You can see , Notes for different amounts , Processing requests are escalated between different job levels , Successfully simulated the process in the introduction .

4. summary

advantage :

  • Decouple the receiver and handler of the request , The client does not need to know the specific processor , Programming only for abstract handlers , Simplifies the client programming process , Reduce the coupling of the system ;
  • When adding a new handler to the system , Just inherit the abstract handler , Re actualize handleRequest() Interface , There is no need to change the original code , Comply with opening and closing principle ;
  • When assigning responsibilities to an object , The responsibility chain model gives the system more flexibility .

shortcoming :

  • The request does not have an explicit recipient , It is possible to encounter the problem that the request cannot be responded ;
  • A long chain of responsibilities , The processing process will be very long .
  • The establishment of responsibility chain is carried out on the client , If not properly established , It may cause a circular call or call failure .

Apply to the environment :

  • There are multiple objects processing the same request , Who will handle it is decided at runtime , The client just needs to send a request to the responsibility chain , It doesn't matter who handles it ;
  • You can dynamically specify a set of objects to handle requests , The client can dynamically create a responsibility chain to handle the request , You can also change the hierarchical relationship between processors in the responsibility chain .
原网站

版权声明
本文为[Grow some hair.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220821493147.html