我怎样才能减少这个功能的样板文件?

How can I reduce boilerplate from this function?

在我的 qooxdoo 应用程序中,我有 4 个按钮。登录、注销、注册和个人资料。每个按钮都有一个动作 class。那些 class 是从一个共同的摘要 class 中提取出来的 class。通过使用命令模式,每次单击按钮时,我都会调用相应 class 的执行函数。函数看起来像这样

    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 个子 class 中实现该执行函数,唯一改变的是变量内容和内容字符串。

我正在考虑使用工厂函数,并且每次 return 基于 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 的某些功能我不知道?

次要点,但是如果您已经有一个 return 语句,则不需要为每个 case 都有 break 语句,因为这足以存在 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]();
}

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

所以在你的摘要 class 你有:

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()