2012-01-05 55 views
2

我已经搜索并阅读了几个小时,但仍无法理解用于创建具有不同方法选择的新对象的基本设计模式(具有相同名称),其取决于其中一个参数。这里有一些代码来解释我正在尝试做什么。 欢迎提供所有建议和替代方法。我希望有人能解放我,形成这种无知的云。 感谢根据对象创建期间的参数选择对象所具有的方法集合 - JavaScript

function BaseConstructor(whichMethods) { 
    if (whichMethods==='a') { 
     // do something to incorporate methodSetA 
    } 
    else if (whichMethods==='b') { 
     // do something to incorporate methodSetB 
    } 

    this.init(); 
}; 

var methodSetA = { 
    init: function() { 
     // do initialisation A way 
    }, 
    speak: function() { 
     alert('i speak AAA way') 
    } 
}; 

var methodSetB = { 
    init: function() { 
     // do initialisation B way 
    }, 
    speak: function(){ 
     alert('i got BBB all the way') 
    } 
}; 

thing = new BaseConstructor('b'); 
// b is an instance of BaseConstructor and has done the bWay init() function 

thing.speak() // return alert 'i got BBB all the way' 

回答

0

您可以使用工厂函数(,为您创建合适的对象常规的函数)做这样的:

function BaseConstructor(whichMethods) { 
    var elem; 
    if (whichMethods==='a') { 
     elem = new MethodSetA(); 
    } else if (whichMethods==='b') { 
     elem = new MethodSetB(); 
    } else { 
     // figure out what to do here if whichMethods is neither of the previous options 
    } 

    elem.init(); 
    return(elem); 
}; 

并调用它作为一个普通函数调用:

var thing = BaseConstructor('b'); 
thing.speak(); 

注意:newBaseConstructor()没有任何用处,因为它是常规函数调用。

+0

明白了,感谢您的及时回复!工厂设计模式 - 我今天肯定已经阅读了5次,并且有点认为这是我需要的,但总是在无关的细节中分散注意力。再次感谢@ jfriend00 – johowie 2012-01-05 03:02:50

0

好了,使用 “方法设置”,你可以遍历并复制到thishere's a demo)做你的方式:

function copy(source, destination) { 
    for(var x in source) { 
     if(source.hasOwnProperty(x)) { 
      destination[x] = source[x]; 
     } 
    } 
} 

function BaseConstructor(whichMethods) { 
    if(whichMethods === 'a') { 
     copy(methodSetA, this); 
    } else if(whichMethods === 'b') { 
     copy(methodSetB, this); 
    } 

    this.init(); 
} 

就个人而言,虽然,我更愿意分配直接到this

+0

谢谢你的建议,并找到一个办法做到这一点“我的路”,我会从你的代码中学习。再次感谢@ minitech – johowie 2012-01-05 03:05:38

0

您正在寻找工厂模式。 例子:

function objectFactory(whichMethods) { 
     if (whichMethods==='a') { 
      return new objectSetA(); 
     } 
     else if (whichMethods==='b') { 
      return new objectSetB() 
     } 
    }; 
    function objectSetA() { 
     this.init = function() { 
     // do initialisation A way 
     }, 
     this.speak = function() { 
      alert('i speak AAA way') 
     } 
    }; 

    function objectSetB() { 
     this.init = function() { 
     // do initialisation B way 
     }, 
     this.speak = function(){ 
      alert('i got BBB all the way') 
     } 
    }; 
    var thing = objectFactory('b'); 
    thing.speak(); 
+0

感谢您的及时和明确的答复,的确我需要一个工厂! @petar – johowie 2012-01-05 03:07:55

+0

说方法应该在各自的构造器的原型上。 – RobG 2012-01-05 04:01:51

+0

@RobG在原型上放置speak()方法是有意义的。你有没有理由不在原型上使用init()方法? – johowie 2012-01-05 06:20:11