命令模式(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.start() } } class StartAnimationCommand { constructor (receiver) { this.receiver = receiver } run () { this.receiver.start() } } setCommand(btn1, new ShowDialogCommand(dialog)) setCommand(btn2, new StartAnimationCommand(animation))