• JS 设计模式五 -- 命令模式


    概念

    命令模式中的命令(command) 指的是 一个执行某些待定事情的指令。

    用一种松耦合的方式来设计程序,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。

    例子

    假设html结构如下:
    <button id="button1">刷新菜单目录</button>
    <button id="button2">增加子菜单</button>
    var setCommand = function(button,func) {
        button.onclick = function(){
            func();
        }
     }; 
     var MenuBar = {
        refersh: function(){
            alert("刷新菜单界面");
        }
     };
     var SubMenu = {
        add: function(){
            alert("增加菜单");
        }
     };
     // 刷新菜单
     var RefreshMenuBarCommand = function(receiver) {
        return function(){
            receiver.refersh();    
        };
     };
     // 增加菜单
     var AddSubMenuCommand = function(receiver) {
        return function(){
            receiver.add();    
        };
     };
    // 刷新菜单 var refershMenuBarCommand = RefreshMenuBarCommand(MenuBar); // 增加菜单 var addSubMenuCommand = AddSubMenuCommand(SubMenu); setCommand(b1,refershMenuBarCommand); setCommand(b2,addSubMenuCommand);

    理解宏命令

    宏命令是一组命令的集合,通过执行宏命令的方式,可以一次执行一批命令。

    这样类似把页面的所有函数方法放在一个数组里面去,然后遍历这个数组,依次执行该方法。

    例子

    var command1 = {
        execute: function(){
            console.log(1);
        }
    }; 
    var command2 = {
        execute: function(){
            console.log(2);
        }
    };
    var command3 = {
        execute: function(){
            console.log(3);
        }
    };
    // 定义宏命令,command.add方法把子命令添加进宏命令对象,
    // 当调用宏命令对象的execute方法时,会迭代这一组命令对象,
    // 并且依次执行他们的execute方法。
    var command = function(){
        return {
            commandsList: [],
            add: function(command){
                this.commandsList.push(command);
            },
            execute: function(){
                for(var i = 0,commands = this.commandsList.length; i < commands; i+=1) {
                    this.commandsList[i].execute();
                }
            }
        }
    };
    // 初始化宏命令
    var c = command();
    c.add(command1);
    c.add(command2);
    c.add(command3);
    c.execute();  // 1,2,3
  • 相关阅读:
    680C. Bear and Prime 100 数学
    Codeforces 681C. Heap Operations 优先队列
    Codeforces C. NP-Hard Problem 搜索
    Codeforces 689C. Mike and Chocolate Thieves 二分
    Codeforces 689B. Mike and Shortcuts SPFA/搜索
    Codeforces Round #223 (Div. 2) E. Sereja and Brackets 线段树区间合并
    Educational Codeforces Round 1 E. Chocolate Bar dp
    Testing Round #12 A,B,C 讨论,贪心,树状数组优化dp
    Educational Codeforces Round 2 E. Lomsat gelral 启发式合并map
    hdu 3706 Second My Problem First 单调队列
  • 原文地址:https://www.cnblogs.com/gaosirs/p/10749367.html
Copyright © 2020-2023  润新知