当前位置:网站首页>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
// request : Notesclass Bill{public:Bill(){}Bill(int iId, string iName, double iAccount){id = iId;name = iName;account = iAccount;}double getAccount(){return this->account;}void print(){printf("\nID:\t%d\n", id);printf("Name:\t%s\n", name.c_str());printf("Account:\t%f\n", account);}private:int id;string name;double account;};
3.2. Abstract processor
// Abstract processorclass Approver{public:Approver(){}Approver(string iName){setName(iName);}// Add superiorvoid setSuperior(Approver *iSuperior){this->superior = iSuperior;}// Processing requestsvirtual void handleRequest(Bill*) = 0;string getName(){return name;}void setName(string iName){name = iName;}protected:Approver *superior;private:string name;};
3.3. Specific handler
3.3.1. Specific handler : group leader
// Specific handler : group leaderclass GroupLeader :public Approver{public:GroupLeader(){}GroupLeader(string iName){setName(iName);}// Processing requestsvoid handleRequest(Bill *bill){if (bill->getAccount() < 10){printf(" group leader %s The bill was processed , Note information :",this->getName().c_str());bill->print();}else{printf(" The team leader has no right to deal with , Transfer to superior ……\n");this->superior->handleRequest(bill);}}};
3.3.2. Specific handler : executive director
// Specific handler : executive directorclass Head :public Approver{public:Head(){}Head(string iName){setName(iName);}// Processing requestsvoid handleRequest(Bill *bill){if (bill->getAccount() >= 10 && bill->getAccount()<30){printf(" executive director %s The bill was processed , Note information :", this->getName().c_str());bill->print();}else{printf(" The supervisor has no authority to deal with , Transfer to superior ……\n");this->superior->handleRequest(bill);}}};
3.3.3. Specific handler : The manager
// Specific handler : The managerclass Manager :public Approver{public:Manager(){}Manager(string iName){setName(iName);}// Processing requestsvoid handleRequest(Bill *bill){if (bill->getAccount() >= 30 && bill->getAccount()<60){printf(" The manager %s The bill was processed , Note information :", this->getName().c_str());bill->print();}else{printf(" The manager has no authority to deal with , Transfer to superior ……\n");this->superior->handleRequest(bill);}}};
3.3.4. Specific handler : Boss
// Specific handler : Bossclass Boss :public Approver{public:Boss(){}Boss(string iName){setName(iName);}// Processing requestsvoid handleRequest(Bill *bill){printf(" Boss %s The bill was processed , Note information :", this->getName().c_str());bill->print();}};
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 .
#include <iostream>#include "ChainOfResponsibility.h"int main(){// Request handler : group leader , Brother Bing , Chunzong , BossApprover *zuzhang, *bingge, *chunzong, *laoban;zuzhang = new GroupLeader(" Brother sun ");bingge = new Head(" Brother Bing ");chunzong = new Manager(" Chunzong ");laoban = new Boss(" Boss Zhang ");zuzhang->setSuperior(bingge);bingge->setSuperior(chunzong);chunzong->setSuperior(laoban);// Create a reimbursement formBill *bill1 = new Bill(1, "Jungle", 8);Bill *bill2 = new Bill(2, "Lucy", 14.4);Bill *bill3 = new Bill(3, "Jack", 32.9);Bill *bill4 = new Bill(4, "Tom", 89);// All shall be submitted to the team leader for approvalzuzhang->handleRequest(bill1); printf("\n");zuzhang->handleRequest(bill2); printf("\n");zuzhang->handleRequest(bill3); printf("\n");zuzhang->handleRequest(bill4);printf("\n\n");system("pause");return 0;}
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 .
边栏推荐
- Preview function implementation of Android kotlin Camera2
- Summary of basic knowledge of Oracle database SQL statement II: data operation language (DML)
- 依图在实时音视频中语音处理的挑战丨RTC Dev Meetup
- Type of sub database and sub table
- 一文彻底搞懂My SQL索引知识点
- Summary of basic knowledge of Oracle database SQL statements I: Data Definition Language (DDL)
- Develop steam education based on scientific skills
- 兔小巢使用记录
- 19 备忘录模式
- Basic operation knowledge of DML and DQL
猜你喜欢

Using KDJ metrics on MT4

Analyzing the role of cognitive theory in maker teacher training

Prompt installremove of the Service denied when installing MySQL service

11 外观模式

Spark Yarn内存资源计算分析(参考)--Executor Cores、Nums、Memory优化配置

FastCorrect:语音识别快速纠错模型丨RTC Dev Meetup

Crawling microblog comments | emotional analysis of comment information | word cloud of comment information

Example of multipoint alarm clock

Implementation and landing of any to any real-time voice change RTC dev Meetup

Flask博客实战 - 实现博客的分类管理
随机推荐
Detailed explanation of the underlying principle of concurrent thread pool and source code analysis
I spring and autumn web Penetration Test Engineer (elementary) learning notes (Chapter 1)
16 解释器模式
读取jar包里面文件夹下的所有文件
steam教育文化传承的必要性
Bee framework, an ORM framework
每周推荐短视频:什么是“计算世界”?
07 适配器模式
Example of multipoint alarm clock
I spring and autumn web Penetration Test Engineer (elementary) learning notes (Chapter 2)
Summary of basic knowledge of Oracle database SQL statements I: Data Definition Language (DDL)
中断中为何不能使用信号量,中断上下文为何不能睡眠
Using KDJ metrics on MT4
兔小巢使用记录
Flask博客实战 - 实现用户管理
Some problems encountered in using swagger in golang
YOLOv5报错:AttributeError: ‘Upsample‘ object has no attribute ‘recompute_scale_factor‘ 的解决方案
12 享元模式
C # read / write TXT file to listview
JVM memory overflow