Use Case: Unit test object creation, any time object construction is complicated.
When piecewise object construction is complicated, provide and API for doing it in a brief and clearly expressed manner.
*A piecewise function is a function built from pieces of different functions over different intervals. *
FooBuilder is used to construct the entity
Foo, its state can be set if needs be with the methods
WithContactPerson(), this fluent API can be chained. Finally the
Create() method returns an instance of
Foo with the internal state set.
Example Use Case Of FooBuilder
In a test this could be used as follows with the assumption
SelectList returns a collection of type
var foo = new FooBuilder();
Example HTML Builder
Code example below from Dmitri Nesteruk
Life without Builder
Manually create some HTML, this will work but its not great.
var sb = new StringBuilder();
Life With A Builder
Here the constructor for HtmlBuilder takes a
rootName and the
AddChild method takes
childText parameters. This is then encapsulating the creation and use of HtmlElement.
// ordinary non-fluent builder
AddChildFluent returns a HtmlBuilder to allow you to chain methods together. This works by returning a reference to the original object. This is called a fluent interface.
var builder = new HtmlBuilder("ul");