不直接调用类的内部方法,而是通过给“指令函数”传递参数,由“指令函数”来调用类的内部方法,命令模式的由来其实是回调函数(callback)的代替品
假设场景
有10个button、每个button所做的事情不一样、目前也不知道具体做什么、接到的任务就是A去写10个按钮、B去写这10个按钮的业务、如果通过命令模式去编写呢?
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><button id="button1">刷新目前</button><button id="button2">添加目前</button><button id="button3">删除目前</button></body></html><script>// 封装行为class MenuBar{constructor(){}refresh(){console.log('刷新菜单目录')}}class SubMenu{constructor(){}add(){console.log('添加菜单目录')}del(){console.log('删除菜单')}}// 把行为封装在命令类中class RefreshMenuBarCommand{constructor(receiver){this.receiver = receiver}execute(){this.receiver.refresh()}}class AddSubmenuCommand{constructor(receiver){this.receiver = receiver}execute(){this.receiver.add()}}class DelSubmenuCommand{constructor(receiver){this.receiver = receiver}execute(){this.receiver.del()}}function setCommand(button, command){button.onclick = function(){command.execute()}}let button1 = document.getElementById('button1')let button2 = document.getElementById('button2')let button3 = document.getElementById('button3')setCommand(button1, new RefreshMenuBarCommand(new MenuBar()))setCommand(button2, new AddSubmenuCommand(new SubMenu()))setCommand(button3, new DelSubmenuCommand(new SubMenu()))</script>
