命令模式(Command Pattern)

定义:请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
目的:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。
场景:在一个快餐店,用户向服务员点餐。服务员将用户的需求记录在清单上。
let dialog = {
    show () {
        console.log('show a dialog')
    }
}

let animation = {
    start () {
        console.log('show animation')
    }
}
let setCommand = (btn, cmd) => {
    btn.onclick = () => {
        cmd.run()
    }
}

class ShowDialogCommand {
    constructor (receiver) {
        this.receiver = receiver
    }

    run () {
        this.receiver.show()
    }
}

class StartAnimationCommand {
    constructor (receiver) {
        this.receiver = receiver
    }

    run () {
        this.receiver.start()
    }
}


setCommand(btn1, new ShowDialogCommand(dialog))
setCommand(btn2, new StartAnimationCommand(animation))

Git地址:https://github.com/skillnull/Design-Mode-Example

相关文章:

  • 2022-02-09
  • 2021-07-30
  • 2022-12-23
  • 2020-05-18
  • 2018-12-11
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2017-12-14
  • 2019-10-25
相关资源
相似解决方案