命令者模式

Command

概述
发布者 Invoker:发布指令;不知道接收者的存在;不知道谁在执行;一个实例
命令者 Commander:通知接收者;一个实例
接收者 Receiver:执行指令,不知道发布者的存在;不知道谁下达的指令;通常有多个实例
发布通知命令者,再由命令者通知接收者执行execute
应用
使用组合模式,将页面各个模块的命令组合起来,再统一下达命令,让他们分别开始初始化、渲染等
参考代码
Command
class Invoker {
  constructor(commander) {
    this.commander = commander
  }
  publish() {
    console.log('Invoker publishing');
    this.commander.execute()
  }
}

class Commander {
  constructor(receiver) {
    this.receiver = receiver
  }
  execute() {
    console.log('Commander notifying');
    this.receiver.execute()
  }
}

class Receiver {
  execute() {
    console.log('Receiver excuting');
  }
}

let receiver = new Receiver()
let commander = new Commander(receiver)
let invoker = new Invoker(commander)
invoker.publish()
页面渲染
Command
class Macro {
  constructor() {
    this.lists = []
  }
  add(commander) {
    this.lists.push(commander)
  }
  publish() {
    console.log('Invoker publishing');
    this.lists.forEach(item => {
      item.execute()
    })
  }
}

class Tabs {
  execute() {
    console.log('Tabs executing');
  }
}

class Swiper {
  execute() {
    console.log('Swiper executing');
  }
}

let tabs = new Tabs()
let swiper = new Swiper()
let macro = new Macro()
macro.add(tabs)
macro.add(swiper)
macro.publish()