js 命令模式 组合模式

* 基本宏命令

var closeDoorCommand = {
	execute: function() {
		console.log("Closing the door...");
	}
};
var openPcCommand = {
	execute: function() {
		console.log("Opening the PC...");
	}
};
var launchQQCommand = {
	execute: function() {
		console.log("launching QQ...");
	}
};

var MacroCommand = function() {
	return {
		commandsList: [],
		add: function(command) {
			this.commandsList.push(command);
		},
		execute: function() {
			for (var i = 0, command; command = this.commandsList[i]; i++) {
				command.execute();
			}
		}
	}
};

var macroCommand = MacroCommand();

macroCommand.add(closeDoorCommand);
macroCommand.add(openPcCommand);
macroCommand.add(launchQQCommand);

macroCommand.execute();
// Closing the door...
// Opening the PC...
// launching QQ...

  

* 树形宏命令

<html>

<head>
    <meta charset="UTF-8">
    <title>macro command</title>
</head>

<body>
    <button id="button">Press me</button>
    <script>
    var MacroCommand = function() {
        return {
            commandsList: [],
            add: function(command) {
                this.commandsList.push(command);
            },
            execute: function() {
                for (var i = 0, command; command = this.commandsList[i]; i++) {
                    command.execute();
                }
            }
        }
    };
    // 打开空调
    var openAcCommand = {
        execute: function() {
            console.log("Opening the Air conditioner...");
        }
    };
    // 打开电视和音响
    var openTvCommand = {
        execute: function() {
            console.log("Opening the TV...");
        }
    };
    var openStereoCommand = {
        execute: function() {
            console.log("Opening the stereo...");
        }
    };
    var macroCommand1 = MacroCommand();

    macroCommand1.add(openTvCommand);
    macroCommand1.add(openStereoCommand);

    // 关门、开电脑、登陆qq
    var closeDoorCommand = {
        execute: function() {
            console.log("Closing the door...");
        }
    };
    var openPcCommand = {
        execute: function() {
            console.log("Opening the PC...");
        }
    };
    var launchQQCommand = {
        execute: function() {
            console.log("launching QQ...");
        }
    };
    var macroCommand2 = MacroCommand();

    macroCommand2.add(closeDoorCommand);
    macroCommand2.add(openPcCommand);
    macroCommand2.add(launchQQCommand);

    // 现在把所有的命令组合成一个超级命令
    var macroCommand = MacroCommand();
    macroCommand.add(openAcCommand);
    macroCommand.add(macroCommand1);
    macroCommand.add(macroCommand2);

    // 绑定到遥控器
    var setCommand = (function(command) {
        document.getElementById("button").onclick = function() {
            command.execute();
        }
    })(macroCommand);
    </script>
</body>

</html>

  

运行结果:

猜你喜欢

转载自www.cnblogs.com/mingzhanghui/p/9282729.html