如何从此功能中减少样板?

时间:2015-11-01 22:43:53

标签: javascript oop qooxdoo

在我的qooxdoo应用程序中,我有4个按钮。登录,注销,注册和个人资料。每个按钮都有一个动作类。这些类是从一个公共抽象类中继承而来的。通过使用命令模式,每次单击按钮时,我都会调用相应类的执行函数。该函数看起来像这样

    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个子类中实现,唯一改变的是变量content和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功能?

2 个答案:

答案 0 :(得分:1)

小问题,但如果您已经有break语句,则不需要为每个case添加return语句,因为这足以存在switch 1}}。

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

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]();
}

答案 1 :(得分: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()

相关问题