本文通过图书馆管理系统中,用户名校验、密码校验、需要增加问题,每次都要增加if判断语句,将其改用责任链模式进行链式调用,为了让代码更加的优雅,我们使用之前学过的建造者模式就代码进行改造。接着我们会介绍责任链模式在我们常用的框架中的运用,最后是责任链模式的优缺点和应用场景。
一、引出问题
小王为老王建了一个图书馆管理系统。随着访问量的不断增加,老王要求进行更多的用户名核查。
[En]
Xiao Wang built a library management system for Lao Wang. With the continuous increase in the number of visitors, Lao Wang asked for more user name checking.
小王准备在用户名判断语句之后添加密码检查语句。老王连忙拦住了想继续换码的小王。如果您稍后添加角色检查和权限检查,您将编写多少条判断语句?
[En]
Xiao Wang is going to add a password check statement after the user name judgment statement. Lao Wang hurriedly stopped Xiao Wang who wanted to continue to change the code. If you add role check and permission check later, how many judgment statements are you going to write?
而且你把软件设计原则中的——开闭原则丢到哪里去了。
可以考虑使用一种模式,将所有的检查方法分离到一个类中,每个类只负责处理自己的检查逻辑,将当前的检查类传递给下一个检查类进行处理,这样每次添加新的逻辑判断时,只需要添加一个检查类。
[En]
You can consider using a mode in which all the check methods are separated into a class, each class is only responsible for dealing with its own check logic, and the current check class is passed to the next check class for processing, so that each time you add a new logic judgment, you only need to add a check class.
就像是一条流水线,每个类负责处理线上的一个环节。
二、责任链模式的概念和使用
实际上,老王提出来的正是行为型设计模式中的——** 责任链模式。
顾名思义,责任链模式将每个责任的步骤串联在一起,在执行下一步之前完成一个步骤。
[En]
The chain of responsibility pattern, as its name suggests, concatenates the steps of each responsibility, and one step is completed before the next step can be performed.