命令模式

2015-06-13  本文已影响37人  JohnSmith

定義

命令模式中的命令指的是一個執行某些特定事情的指令。

要點

核心代碼

var RefreshMenuBarCommand = function(receiver) {
    return {
        execute: function() {
            receiver.refresh();
        }
    };
};
var setCommand = function(button, command) {
    button.onclick = function() {
        command.execute();
    };
};
var MenuBar = {
    refresh: function() {
        // ......
    }
};

var refreshMenuBarCommand = RefreshMenuBarCommand(MenuBar);
setCommand(button1, refreshMenuBarCommand);
\\ 宏命令
var MacroCommand = function() {
    return {
        commandsList: [],
        add: function(command) {
            this.commandsList.push(command);
        },
        execute: function() {
            for (var i = 0, command; command = this.commandsList[i++];) {
                command.execute();
            }
        }
    };
};

var macroCommand = MacroCommand();
macroCommand.add(command1);
macroCommand.add(command2);
macroCommand.add(command3);
macroCommand.execute();
上一篇下一篇

猜你喜欢

热点阅读