i implement builder using closures in javascript. feel can done, struggling put code.
i have feel there better solution leveraging partial application.
function builder() { this.spec = {}; } builder.prototype.withfoo = function(value) { this.spec.foo = value; return this; }; builder.prototype.withbar = function(value) { this.spec.bar = value; return this; }; builder.prototype.build = function() { var result = {}; result.foo = this.spec.foo; result.bar = this.spec.bar; this.spec = {}; // avoid accidentally using same builder repeatedly. return result; }; var builder = new builder(); builder.withfoo('foo value') .withbar('foo value') .build(); // { foo: 'foo value' , bar: 'bar value' }
can me this?
edit: key thing here want object instantiated lazily.
here alternative approach:
function builder(obj){ return obj; }
this called fowler , martin "identity builder" , quite common in enterprise architecture. has advantage of supporting arbitrarily nested hierarchies of objects , sub objects , generic.
var mybuildobject = builder({ spec: { foo: foo, bar: bar } });
it more though, can specify arrays:
var mybuildobject = builder({ spec: [....] });
it can extended , subclassed more sophisticated builders can in turn return builder.call(this, obj)
after decorating it.
it can specify getters/setters.
Comments
Post a Comment