JavaScript 设计模式--串行任务模式,命令模式

in JavaScript with 0 comment

串行任务模式

//Chain of Responsibility ,职责链模式,即串行任务模式
      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()

命令模式 Command

class Receiver {
        do() {
          console.log('最终干活的人')
        }
      }
      class Command{
        constructor(receiver) {
          this.receiver = receiver
        }
        action(){
          console.log('传话的')
          this.receiver.do()
        }
      }
      class Invoker {
        constructor(command) {
          this.command = command
        }
        invoke() {
          console.log('我要人帮我干一件大事...')
          this.command.action()
        }
      }
      let worker = new Receiver()
      let agent = new Command(worker)
      let boss = new Invoker(agent)
      boss.invoke()
评论已关闭.