JavaScript 设计模式之组合模式

组合模式

组合模式将对象组合成树形结构,以表示“部分-整体”的层次结构。除了用来表示树形结构以外,组合模式的另一个好处是通过对象的多态性表现。

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值