组合模式
组合模式将对象组合成树形结构,以表示“部分-整体”的层次结构。除了用来表示树形结构以外,组合模式的另一个好处是通过对象的多态性表现。
let MainCommand = function () {
return {
commandsList: [],
add: function (command) {
this.commandsList.push(command);
},
execute: function () {
for (let i = 0, command; (command = this.commandsList[i++]); ) {
command.execute();
}
},
};
};
// 打开电视和音响命令
let openTvCommand = {
execute: function () {
console.log("打开电视");
},
};
let openSoundCommand = {
execute: function () {
console.log("打开音响");
},
};
let mycommand1 = MainCommand();
mycommand1.add(openTvCommand);
mycommand1.add(openSoundCommand);
// 关门和打开电脑命令
let closeDoorCommand = {
execute: function () {
console.log("关门");
},
};
let openPcCommand = {
execute: function () {
console.log("打开电脑");
},
};
let mycommand2 = MainCommand();
mycommand2.add(closeDoorCommand);
mycommand2.add(openPcCommand);
// 总命令
let mycommand = MainCommand();
mycommand.add(mycommand1);
mycommand.add(mycommand2);
// 执行按钮点击事件
let time1;
let setCommand = (function (command) {
document.getElementById("mainCommand").addEventListener("click", function () {
command.execute();
console.log(command);
this.disabled = true;
let that = this;
time1 = window.setTimeout(function () {
that.disabled = false;
}, 3000);
});
})(mycommand);