Home> Java> javaTutorial> body text

Romance of the Three Kingdoms: Chain of Responsibility Model

Release: 2023-08-28 15:16:25
forward
827 people have browsed it

Hello everyone,Today I will share with you theChain of responsibility modelin the design pattern. Use appropriate life stories and real project scenarios to talk about the design pattern, and finally summarize the design pattern in one sentence.

Story

Two days ago, I read The Romance of the Three Kingdoms again and saw Guan Yu in Cao Ying My heart was in Han, and I heard that Liu Bei was at Yuan Shao's place, and then he performed "pass five passes and kill six generals".

Romance of the Three Kingdoms: Chain of Responsibility Model

Guan Yu passed five levels and killed six generals Main content:

  • The first level, Dongling Pass , beheaded the guard general Kong Xiu.

    Dongling Pass, the guarding general named Kong Xiu was originally a member of the Yellow Turbans. After surrendering to Cao Cao, he was ordered to defend Dongling Pass with 500 people. When Guan Yu's motorcade passed the pass, Kong Xiu asked for the customs clearance document and clashed with Guan Yu. After only one turn, he was killed by Guan Yu.

  • The second level is Luoyang Pass, Meng Tan and Han Fu.

    Guan Yu passed Dongling Pass, and when he was about to cross Luoyang, Han Fu and Meng Tan blocked the road with antlers. First, Meng Tan challenged Guan Yu, but he fell out with Guan Yu and lost the fight. Meng Tan turned his horse and ran back, luring Guan Gong to chase him, so that Han Fu could shoot arrows from behind and capture Guan Gong. But who would have thought that Guan Gong's red rabbit horse was so fast that he could catch up from behind. Meng Tan, chopped Meng Tan in one stroke. Han Fu panicked and shot an arrow, hitting Guan Gong in his left arm. Guan Gong endured the arrow wound, rushed through the antlers, killed Han Fu with a single blow, and then crossed Luoyang.

  • #The third pass is Bishui Pass, Bian Xi.

    After learning that Guan Yu had passed the pass and beheaded his generals, and that Kong Xiu, Han Fu, and Meng Tan at Dongling Pass had all been killed, Bian Xi thought to himself that it was difficult to resist Guan Gong. So he pretended to welcome Guan Gong, and arranged for a swordsman in Zhenguo Temple to wait for an opportunity to kill Guan Gong. Fortunately, Pu Jing, the old abbot of Zhenguo Temple, warned him that Guan Gong was aware of the conspiracy, fell out with Bian Xi, and killed Bian Xi with a sword, so Guan Gong passed Sishui Pass.

  • #The fourth level, Wang Zhi.

    This Wang Zhi is Han Fu's relative. Hearing that Han Fu was killed by Guan Gong, he was very angry, so he wanted to avenge Han Fu. When Guan Gong arrived in Xingyang, Wang Zhi hosted a banquet in the post for Guan Gong and his two wives. But Hu Ban was secretly sent to set fire to Guan Gong, hoping to burn him to death. But Hu Ban reported the secret to Guan Yu because Guan Gong brought a letter to his father Hu Hua. Guan Yu and the two imperial wives were able to escape from the palace in advance, but Hu Ban pretended to set fire to confuse Wang Zhi. However, Wang Zhi later found out and killed Hu Ban. When he came to pursue Guan Yu, he was killed by Guan Yu, so Guan Gong passed Xingyang.

  • The fifth level, the crossing of the Yellow River, Qin Qi.

    This Qin Qi is not only Xiahou Dun's favorite general, but also the nephew of the old general Cai Yang. He was ordered to guard the Yellow River ferry and check the passing ships. When Guan Gong arrived at the ferry of the Yellow River, he was looking for a boat to cross the river, but was stopped by Qin Qi. Qin Qi not only refused to let Guan Gong and others cross the river, but uttered arrogant words, which finally angered Guan Gong and was beheaded by Guan Gong

This is the entire process of Guan Yu passing five levels and killing six generals.

This storyline reminds me of a design pattern:Chain of Responsibility Pattern.

In fact, there are many chain of responsibility models in our lives. For example: Basically every company has its own OA system, which mainly provides functions such as basic employee information, leave requests, time off, and reimbursement. If I need to take two days off for something, I log in to the OA system and initiate leave approval.

Because the company has the following regulations regarding the length of leave time:

is less than or equal to half a day, and the approval process is: Project leader

is more than half a day, less than or equal to 1 day , Approval link: Project leader Technical Director

More than 1 day, Approval link: Project leader Technical Director Boss

It can be seen that I am responsible for the project during the leave approval process Human Technical Director Boss.

What exactly is the chain of responsibility design pattern?

What is the chain of responsibility model?

The English explanation of the chain of responsibility model is:

Avoid coupling the sender of a request to its receiver bygiving more than one object a chance to handle the request.Chainthe receiving objects and pass the request along the chain until anobject handles it.

Chain of Responsibility Pattern treats each node in the chain as an object. Each node handles different requests, and the next node object is automatically maintained internally. When a request is issued from the head end of the chain, it will be passed to each node object along the preset path of the responsibility chain until it is processed by an object in the chain. It belongs to theBehavioral Design Pattern.

General Code of Responsibility Chain Mode

Java implements the responsibility chain design pattern as follows:

public abstract class Handler { protected Handler nextHandler = null; public abstract void handle(); public Handler getNextHandler() { return nextHandler; } public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } } public class HandlerA extends Handler{ @Override public void handle() { if(nextHandler == null){ System.out.println("HandlerA handle ..."); }else{ nextHandler.handle(); } } } public class HandlerB extends Handler{ @Override public void handle() { if(nextHandler == null){ System.out.println("HandlerB handle ..."); }else{ nextHandler.handle(); } } } public class HandlerC extends Handler{ @Override public void handle() { if(getNextHandler() == null){ System.out.println("HandlerC handle ..."); }else{ getNextHandler().handle(); } } } //测试 public class Client{ public static void main(String[] args) { Handler handlerA = new HandlerA(); Handler handlerB = new HandlerB(); handlerA.setNextHandler(handlerB); handlerA.handle(); } }
Copy after login

Run result:

HandlerC handle ...
Copy after login

From the above code, we can draw UML diagram:

Romance of the Three Kingdoms: Chain of Responsibility Model


## From the UML diagram, we can see that there are two types of responsibility chain patterns. A very important role:

(1), abstract handler role (Handler)

Define the interface for processing requests. An interface can also provide a method to set and return a reference to the next object. This role is usually implemented by a Java abstract class or Java interface.

(2), Specific handler roles (HandlerA, HandlerB, HandlerC)

After receiving the request, the specific handler can choose to process the request, or The request is passed to the next object. Since the specific handler holds a reference to the next home.

责任链模式的优缺点

  • 优点:请求和处理分开,两者解耦,提供系统的灵活性。
  • 缺点:性能能问,一个链非常长的时候,非常耗时。因为我们避免建立很长的链。

生活中的案例

在日常生活中,责任链模式是比较常见的。我们平时处理工作中的一些事务,往往是各部门协同合作来完成某一个任务的。而每个部门都有各自的职责,因此,很多时候事情完成一半,便会转交到下一个部门,直到所有部门都审批通过,事情才能完成。

责任链模式主要解耦了请求与处理,客户只需将请求发送到链上即可,不需要关心请求的具体内容和处理细节,请求会自动进行传递,直至有节点对象进行处理。

责任链模式主要适用于以下应用场景:

  • 多个对象可以处理同一请求,但具体由哪个对象处理则在运行时动态决定。
  • 在不明确指定接收者的情况下,向多个对象中的一个提交请求。
  • 可动态指定一组对象处理请求。

请假流程的代码实现

下面我们来对,前面的案例:OA上请假流程做一个Java代码的实现。

抽象处理者:领导类

public abstract class Leader { private Leader next; public void setNext(Leader next) { this.next = next; } public Leader getNext() { return next; } //处理请求的方法 public abstract void handleRequest(double LeaveDays); }
Copy after login

项目负责人

public class ProjectLeader extends Leader { @Override public void handleRequest(double LeaveDays) { if (LeaveDays <= 0.5) { System.out.println("项目负责人批准您请假" + LeaveDays + "天。"); } else { if (getNext() != null) { getNext().handleRequest(LeaveDays); } else { System.out.println("请假天数太多,没有人批准该假条!"); } } } }
Copy after login

技术总监

public class TechnicalDirectorLeader extends Leader { @Override public void handleRequest(double LeaveDays) { if (LeaveDays <= 1) { System.out.println("技术总监批准您请假" + LeaveDays + "天。"); } else { if (getNext() != null) { getNext().handleRequest(LeaveDays); } else { System.out.println("请假天数太多,没有人批准该假条!"); } } } }
Copy after login

Boss

public class BossLeader extends Leader { @Override public void handleRequest(double LeaveDays) { if (LeaveDays >= 2 && LeaveDays <= 30) { System.out.println("Boss批准您请假" + LeaveDays + "天。"); } else { if (getNext() != null) { getNext().handleRequest(LeaveDays); } else { System.out.println("请假天数太多,没有人批准该假条!"); } } } }
Copy after login

发起审批

public class LeaveApproval { public static void main(String[] args) { //组装责任链 Leader projectLeader = new ProjectLeader(); Leader technicalDirectorLeader = new TechnicalDirectorLeader(); Leader bossLeader = new BossLeader(); projectLeader.setNext(technicalDirectorLeader); technicalDirectorLeader.setNext(bossLeader); //请假两天,提交请假流程,开启审批环节, projectLeader.handleRequest(2); } }
Copy after login

审批结果

Boss批准您请假2.0天。
Copy after login

如果请假天数是31天,审批结果

请假天数太多,没有人批准该假条!
Copy after login

整个请假流程为:

Romance of the Three Kingdoms: Chain of Responsibility Model


Change this flow chart to vertical:

Romance of the Three Kingdoms: Chain of Responsibility Model


Just like this, one by one, wouldn’t it be easier to use the above two examples and two pictures to understand the chain of responsibility model?

It’s useless to brag yourself. Let’s take a look at how the masters use the chain of responsibility model.

How do the big guys use it

In frameworks such as Spring and Mybatis, the chain of responsibility model is used. Let’s start with See how it is used in Spring.

In theorg.springframework.web.servlet.DispatcherServletclass in Spring MVC:

Romance of the Three Kingdoms: Chain of Responsibility Model


getHandler方法的处理使用到了责任链模式,handlerMappings是之前 Spring 容器初始化好的,通过遍历handlerMappings查找与request匹配的Handler, 这里返回HandlerExecutionChain对象。这个HandlerExecutionChain对象到后面执行的时候再分析为什么返回的是这样一个对象。

@Nullable protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { if (this.handlerMappings != null) { for (HandlerMapping mapping : this.handlerMappings) { HandlerExecutionChain handler = mapping.getHandler(request); if (handler != null) { return handler; } } } return null; }
Copy after login

以上便是责任链模式在Spring的具体使用

总结

本文通过关二爷的过五关斩六将和OA系统中的请假审批流程,完美的解释了责任链设计模式。

The above is the detailed content of Romance of the Three Kingdoms: Chain of Responsibility Model. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Java后端技术全栈
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!