2015-11-01 65 views
1

在我的qooxdoo应用程序中,我有4个按钮。登录,注销,注册和配置文件。每个按钮都有一个动作类。这些类是从一个共同的抽象类中分类的。通过使用命令模式,每次单击按钮时,我都会调用相关类的execute函数。该功能看起来像这样如何从此功能减少样板?

execute: function() { 
     var contentString = "login-form"; 
     //do some generic stuff 

     if (win.getContentString() === contentString) { 
      //do some generic stuff 

     } else { 
      var content = new myapp.apps.userActions.SLoginForm(); 
      //do some more generic stuff 

     } 
    } 

即执行功能在所有4子类和改变的唯一的东西得以实施是变量的内容和contentString。

我在考虑使用工厂函数,并且每次都根据contentString变量返回适当的对象。

execute:function(){ 
    var contentString = "login-form"; 
    this.doTheGenericStuff(contentString); 
}, 

doTheGenericStuff: function(contentString){ 
    //do the generic stuff 
    var content = this.getTheObject(contentString); 
    //do some more generic stuff 
}, 

getTheObject: function(contentString){ 
    switch(contentString){ 
      case "login-form": 
       return new myapp.apps.userActions.SLoginForm(); 
      break; 
      case "register-form": 
       return new myapp.apps.userActions.SRegisterForm(); 
      break; 
      //etc 
    } 
} 

虽然这似乎确定(没有测试它尚未)我不喜欢它多,因为我每次添加新的行动时间,我必须更新工厂函数。有没有更聪明的方法来实现这一目标?也许我不知道的JavaScript的一些功能?

回答

1

我觉得在这种情况下使用template method pattern更合适。

所以你的抽象类的有:

getMyContentString: function() { return "login-form"; //or any default value }, 

getMyContent: function() { return new myapp.apps.userActions.SLoginForm() }, 

execute: function() { 
     var contentString = getMyContentString(); // to be overridden 
     //do some generic stuff 

     if (win.getContentString() === contentString) { 
      //do some generic stuff 

     } else { 
      var content = getMyContent(); 
      //do some more generic stuff 

     } 
    } 

而且每个子对象只需要提供相应的getMyContentString()getMyContent()

1

小点,但你并不需要为每个casebreak语句,如果你已经有了一个return声明,因为这是足以存在switch

您可以传递一个额外的参数,并使用括号表示法而不是点表示法来调用构造函数。

execute:function(){ 
    var contentString = "login-form"; 
    var objectType = "SLoginForm"; 
    this.doTheGenericStuff(contentString, objectType); 
}, 

doTheGenericStuff: function(contentString, objectType){ 
    //do the generic stuff 
    var content = this.getTheObject(objectType); 
    //do some more generic stuff 
}, 

getTheObject: function(objectType){ 
    return new myapp.apps.userActions[objectType](); 
}