责任链模式介绍
责任链模式定义:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
责任链模式的优点:
1、解耦了请求的发送者和多个接收者之前的复杂关系
2、方便链路中的节点对象灵活的拆分重组
3、手动指定起始节点,可以不是从链路中第一个节点开始
责任链类实现
class Chain {
constructor (fn) {
this.fn = fn // fn为要封装的处理函数
this.sucessor = null // sucessor为下一个节点
}
// 设置下一个节点
setNext (sucessor) {
this.sucessor = sucessor
}
// 设置处理函数
handle () {
// 执行fn,若result返回为nextSucessor,表示要执行下一个节点
const result = this.fn.apply(this, arguments)
if (result === 'nextSucessor') {
console.log(this)
if (this.sucessor) {
this.sucessor.handle.apply(this.sucessor, arguments)
}
}
}
}
具体案例:
如图,根据姓名搜索简历时,搜索结果按照待处理,合适,面试,待定,不合适的顺序依次展示不为零的列表。这是典型的一个请求,多个处理请求对象的例子。
首先,定义处理函数
let pending = function() {
if(待处理不为零){跳转到待处理}
else { return 'nextSucessor'}
}
let appropriate = function() {
if(合适不为零){跳转到合适}
else { return 'nextSucessor'}
}
let interview = function() {
if(面试不为零){跳转到面试}
else { return 'nextSucessor'}
}
let undetermined = function() {
if(待定不为零){跳转到待定}
else { return 'nextSucessor'}
}
let interview = function() {
if(面试不为零){跳转到面试}
else { return 'nextSucessor'}
}
然后,将处理函数封装到责任链中
let pendingChain = new Chain(pending) // 待处理链
let appropriateChain = new Chain(appropriate) // 合适链
let interviewChain = new Chain(interview)
let undeterminedChain = new Chain(undetermined) // 待定链
let unappropriateChain = new Chain(unappropriate) // 不合适链
最后,设置责任链的处理顺序
pendingChain.setNext(appropriateChain)
appropriateChain.setNext(undeterminedChain)
interviewChain.setNext(undeterminedChain)
undeterminedChain.setNext(unappropriateChain)
unappropriateChain.setNext(lastChain)
pendingChain.handle()