Builder
Intent
The intent of the builder design pattern is to separate the construction of a complex object from its representation.
By doing so, the same construction process can create different representations.
Problem
Creating and assembling the parts of a complex object directly within a class is inflexible. It commits the class to creating a particular representation of the complex object and makes it impossible to change the representation later independently from (without having to change) the class.
How can a class (the same construction process) create different representations of a complex object?
How can a class that includes creating a complex object be simplified?
How can telescoping constructor problem be solved.
Solution
Encapsulate creating and assembling the parts of a complex object in a separate Builder object. This allows us to do a piecewise construction of complex object.
A class delegates object creation to a Builder object instead of creating the objects directly.
A class can delegate to different Builder objects to create different representations of a complex object.
Advantages
✅ Allows you to vary a product's internal representation. ✅ Encapsulates code for construction and representation. ✅ Provides control over steps of construction process.
Disadvantages
❌ A distinct ConcreteBuilder must be created for each type of product. ❌ Builder classes must be mutable. ❌ May hamper/complicate dependency injection.
Fluent Interfaces
fluent interface
is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL).The term was coined in 2005 by Eric Evans and Martin Fowler.
Note that, a "fluent interface" means more than just method cascading via chaining; it entails designing an interface that reads like a DSL, using other techniques like "nested functions and object scoping".
Interesting read about fluent interface can be found here.
Fluent Interface are evil.
Interesting take on Builder pattern v/s FluentInterfaces.
Last updated