命令模式(Command Pattern)
1 2 3 |
定义:请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。 目的:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。 场景:在一个快餐店,用户向服务员点餐。服务员将用户的需求记录在清单上。 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
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)) |