Date Published: July 21, 2020
The Builder Pattern is a useful pattern of object-oriented software that spearates the construction of an object from its representation.
The Builder Design Pattern can be used in many ways throughout object-oriented programming. However, one of its most useful applications is in simplifying unit tests. In unit tests, you tend to care only about one or two properties of an object, even though its constructor might require many parameters to be passed. Since many of these parameters are irrelevant, your tests can end up being rather cluttered. The Builder Pattern can help.
Separates the construction of a complex object from its representation so that the same construction process can create different representations.
Essentially, the Builder Pattern allows you to separate logic from data in order to reuse constructor logic to create the exact same thing, just with different data.
StringBuilder and fluent APIs are not the Builder Pattern.
The Builder Pattern entails creating a class of name
SomeTypeBuilder, which has various methods
WithSomeParameter(var someParameter) and
Build(). Using the parameter methods - each of which returns
this - and the build method, you can return an instance of
SomeType with the parameters you care about set, and all other parameters set to default values. Using this pattern in unit testing declutters your tests, thus increasing readability.
In the formal definition, you have a Builder, which is used by a Director and implemented by a Concrete Builder, which produces a Product.
Director - controls logic, puts steps in order
Builder - defines steps
Concrete Builder - provides implementation
Product - produced by the preceding three components
The Builder Pattern more generally
Thanks for reading! I hope you find this and other articles here at ilyanaDev helpful! Be sure to follow me on Twitter @ilyanaDev.