Builder Pattern应如何处理未定义的选项?

时间:2016-01-14 22:19:07

标签: javascript node.js design-patterns undefined builder-pattern

我在JavaScript中构建一个Builder,我不确定构建器通常如何处理选项的未定义值。我想如果字段未定义,Builder不会将可选字段附加到对象。这对建造者来说是否可以接受?如果没有,会有什么替代方案?

以下是第一个实现的示例,其中构建器未附加未定义的可选项:

生成器:

function Thing(required1, required2, required3) {
 //check required params 

  var fields = {
    required1: required1, 
    required2: required2, 
    required3: required3
  };  

  var _withOptionalParam = function(param) {
    if(!param) { return this; } //exit function early if param is undefined

    fields.param = param; 
    return this; 
  };

  var _build = function() {
    var result = fields;
    return result;
  };

  var builder = {
    withOptionalParam: _withOptionalParam,
    build: _build
  };

  return builder;
}

行动中:

var thing = new Thing("foo","bar","baz").withOptionalParam(undefined).build();

//'thing' should be 
// { 
//  required1:"foo", 
//  required2:"bar", 
//  required3:"baz"
// };
//

提前致谢!

1 个答案:

答案 0 :(得分:0)

我认为您在this函数中丢失了_withOptinalParam的上下文。您可以bind fields this作为function Thing(required1, required2, required3) { //check required params var fields = { required1: required1, required2: required2, required3: required3 }; var _withOptionalParam = function(param) { if(!param) { return this; } //exit function early if param is undefined fields.param = param; return this; }; var _build = function() { var result = fields; return result; }; var builder = { withOptionalParam: _withOptionalParam.bind(fields), build: _build }; return builder; } var thing = new Thing("foo","bar","baz").withOptionalParam(undefined); console.log( thing ); //'thing' should be // { // required1:"foo", // required2:"bar", // required3:"baz" // }; //上下文对象。

<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
{{1}}