Builder pattern
Table of contents
Intend
The builder pattern is to separate the construction of a complex object from its representation, allowing for a step-by-step construction process.
It suggests that you extract the object construction code out of its own class and move it to separate objects called builders.
Builder pattern often uses a fluent interface, which facilitates method chaining.
Method Chaining: By returning the Builder instance, you can chain multiple method calls together in a single, fluent expression. This makes the code more readable and concise.
Key points to consider when creating a builder pattern:
The main class (
Phone
) constructor should be private because object construction is managed only by theBuilder
class.The private constructor should accept only a
Builder
class instance, which initializes the values of the main class attributes.The main class should not provide any setter methods; it should contain only getter methods to create an immutable object.
The
Builder
class should be static.All the
Builder
class methods should return theBuilder
instance (fluent interface).Finally, the
build
method should return the fully constructed object of the main class, not theBuilder
instance
Examples where the builder pattern is used in Java
StringBuilder and StringBuffer
java.nio.file.Path and java.nio.file.Paths
Stream.Builder
LocalDateTime, LocalDate and LocalTime
Subscribe to my newsletter
Read articles from Raghu Annamalai directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by