美文网首页
JS设计模式5 - 命令模式

JS设计模式5 - 命令模式

作者: 转角遇见一直熊 | 来源:发表于2017-03-17 17:40 被阅读48次

    命令模式

    命令模式

    目标

    封装函数调用,请求,操作。解耦对象的调用和方法的实现。

    何时使用

    1. 需要回调能力
    2. 请求需要执行很多次,或者按照一定顺序,或者需要保存调用日志。
    3. 请求者需要和处理请求的对象解耦。

    举例

    线程池用来异步执行一些任务。用命令模式可以让线程池不需要知道具体实现,它只需要保存任务,并触发任务。

    代码

    下面看看如何用命令模式改造下面代码

    (function(){
     
      var carManager = {
     
        // request information
        requestInfo: function( model, id ){
          return "The information for " + model + " with ID " + id + " is foobar";
        },
     
        // purchase the car
        buyVehicle: function( model, id ){
          return "You have successfully purchased Item " + id + ", a " + model;
        },
     
        // arrange a viewing
        arrangeViewing: function( model, id ){
          return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
        }
     
      };
     
    })();
    

    当我们需要使用carManager的时候,我们必须这样使用
    carManager. buyVehicle('xxx','xxx')
    这样当buyVehicle函数名称改变的时候,调用者不得不改变自己的代码。

    如果想改进这坨代码,使用Java或者C#则必须要定义接口,那么用JavaScript如何做呢?我们来看看JavaScript的命令模式。

    carManager.execute = function ( name ) {
        return carManager[name] && carManager[name].apply( carManager, [].slice.call(arguments, 1) );
    };
    
    

    最后,我们可以这样调用

    carManager.execute( "arrangeViewing", "Ferrari", "14523" );
    carManager.execute( "requestInfo", "Ford Mondeo", "54323" );
    carManager.execute( "requestInfo", "Ford Escort", "34232" );
    carManager.execute( "buyVehicle", "Ford Escort", "34232" );
    

    总结

    动态语言可以让我们更接近思想的核心,相比如最上面的图形,JavaScript的实现无疑一针见血。

    看一个复杂一点的例子:
    http://codepen.io/ImagineProgramming/pen/reyOJv

    相关文章

      网友评论

          本文标题:JS设计模式5 - 命令模式

          本文链接:https://www.haomeiwen.com/subject/hgoenttx.html