JavaScript中的职责链模式

86 阅读1分钟

介绍

※ 一步操作可能分为多个职责角色来完成

※ 把这些角色都分开,然后用一个链串起来

※ 将发起者和各个处理者进行隔离

实现代码(ES6)

class Action {
    constructor(name){
        this.name = name 
        this.nextAction = null
    }
    setNextAction(action){
        this.nextAction = action
    }
    handle(){
        console.log(`${this.name} 审批`)
        if(this.nextAction != null){
            this.nextAction.handle()
        }
    }
}

//测试代码

let a1 = new Action('组长')
let a2 = new Action('经理')
let a3 = new Action('总监')

a1.setNextAction(a2)
a2.setNextAction(a3)

a1.handle()

JS中的链式操作

◆ 职责链模式和业务结合比较多, JS 中能联想到链式操作

◆ jQuery的链式操作 Promise.then 的链式操作

设计原则

● 发起者于各个处理者进行隔离

● 符合开放封闭原则