2015-11-01 62 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](); 
}