命令模式

命令模式(Command Pattern)又称 事务模式,将请求封装成对象,将命令的 发送者接受者 解耦。本质上是对 方法调用的封装

生活实例·只能家居

我们原来分装电灯类是这样子的
    
      // 电灯类
      class Light{
        constructor(name){
          this.name = name;
        }
        on(){
          console.log('打开',this.name)
        }
        off(){
          console.log('关掉',this.name)
        }
        // 只有通过调用这个函数才能真正起到关灯的作用,因为这个是对灯的指令的入口
        execute(command){
          console.log("各种处理,然后开关灯");
          if(command === 'on'){
            this.on();
          }
          else if(command === 'off'){
            this.off();
          }
        }
      }

      const light = new Light('卧室灯');
      light.on(); // 无效,无法真正开灯
      light.execute('on'); // 开灯 有效
    
  
将灯的控制行为抽离出来,独立成了类,形成发送命令类
    
      // 电灯类
      class Light{
        constructor(name){
          this.name = name;
        }
        on(){
          console.log('打开',this.name)
        }
        off(){
          console.log('关掉',this.name)
        }
      }

      // 电灯指令类
      class LightCommand {
        constructor(name){
          super();
          this.name = name;
          // 将控制电灯的指令抽离出来独立成类,为了这个指令能准确控制电灯,需要在内部初始化电灯类
          this.light = new Light(name);
        }

        // 这个本来是在电灯类里面的,被独立出来了
        execute(command){
          if(command === 'on'){
            this.light.on();
          }
          else if(command === 'off'){
            this.light.off();
          }
        }
      }

      // 通过调用电灯指令类就可以去控制电灯
      const lightCommand = new LightCommand('卧室灯');
      lightCommand.execute('on'); // 开灯
      // 此时,使用者并不知道灯的打开方式是怎样的,也就不会去调用 light 的 on方法了,而是交给指令去操作,使用者只需要发送指令。
    
  
当这指令抽离得多了以后,可以自由组合成一个遥控器,形成智能家居的遥控器。比较灵活。