命令模式:
什么叫命令模式:
将一个请求封装成一个对象, 从而让你使用不同的请求把客户端参数化, 对请求排队或者记录请求日志, 可以提供命令的撤销和恢复功能.
命令模式主要有四个部分:
命令对象 (command): 需要执行的命令都在此声明
委托者 (client): 创建命令对象, 并把它传递给调用者
调用者 (invoker): 使用命令对象并调用它上面的方法
接受者 (receiver): 实际干活的角色, 命令传递到这里被实际执行
上代码来理解
- <html>
- <head></head>
- <body>
- <button id='but'> 更新 </button>
- <button id='but1'> 新增 </button>
- </body>
- <script>
- var button1 = document.getElementById('but')
- var button2 = document.getElementById('but1')
- // 封装方法
- var bindClick = function(button, func) {
- button.onclick = func;
- };
- // 一方法
- var MenuBar = {
- refresh: function() {
- console.log('refresh');
- },
- };
- // 二方法
- var SubMenu = {
- add: function() {
- console.log('add');
- },
- del: function() {
- console.log('del');
- },
- };
- // 运行
- bindClick(button1, MenuBar.refresh);
- bindClick(button2, SubMenu.add);
- </script>
- </HTML>
宏命令: 也可以叫做一个命令运行多个事件
- <HTML>
- <head></head>
- <body>
- <button id='but'> 拉萨 JFK 撒 </button>
- <button id='but1'> 拉萨 JFK 撒 </button>
- </body>
- <script>
- var button1 = document.getElementById('but')
- var button2 = document.getElementById('but1')
- // 命令 1
- var closeDoorCommand = {
- execute: function() {
- console.log('close door');
- },
- };
- // 命令 2
- var openPcCommand = {
- execute: function() {
- console.log('open pc');
- },
- };
- // 命令 3
- var openQQCommand = {
- execute: function() {
- console.log('login qq');
- },
- };
- // 宏命令对象
- var MacroCommand = function() {
- return {
- commandList: [],
- add: function(command) {
- this.commandList.push(command);
- },
- execute: function() {
- for (var i = 0, command; command = this.commandList[i++];) {
- command.execute();
- }
- },
- };
- };
- // 实例
- var macroCommand = MacroCommand();
- macroCommand.add(closeDoorCommand);
- macroCommand.add(openPcCommand);
- macroCommand.add(openQQCommand);
- macroCommand.execute();
- </script>
- </HTML>
具体类是对基于类的编程语言的最好解释, 并且同抽象类的理念联系紧密. 抽象类定义了一个接口, 但并不需要提供对它的所有成员函数的实现. 它扮演着驱动其它类的基类角色. 被驱动类实现了缺失的函数而被称为具体类. 命令模式背后的一般理念是为我们提供了从任何执行中的命令中分离出发出命令的责任, 取而代之将这一责任委托给其它的对象
用图来讲解下
就是这么简单
来源: http://www.bubuko.com/infodetail-2965533.html