The Builder Pattern (using immutability)

Опубликовано: 18 Май 2026
на канале: Hector Fontanez
593
6

The Builder Pattern

Example from Joshua Bloch's book: Effective Java

Design Patterns Github: https://github.com/prof-fontanez/Desi...

Benefits:
1) Better alternative to the JavaBeans pattern because it doesn't preclude making the class immutable.
2) Allows the object to be built in steps rather than all in one. (You may have scenarios where it might be undesirable to provide a partially configured object.)
3) - If immutable - provides thread safety

This pattern is also well-suited for class hierarchies (will show on a future video)

The blueprint:

1) Create your widget class, but make the constructor private.
2) Constructor must take a Builder as an argument.
2a) Initialize all fields by obtaining the data from the builder object.
3) Add all your data members (fields). Optionally, make them all final (code for immutability).
4) Add getters. Add setters unless coding for immutability.
4a) getters should return either an immutable object or a defensive copy (clone)
4) Include the Builder class as a public static inner class.
5) In the builder, declare all the fields found in the widget class.
5a) Required fields shall be final.
6) Create the Builder constructor taking all required fields as parameters.
7) Add "setters" for each optional member, but make the method return the Builder.
8) Lastly, add a "build()" method on the Builder that returns a new instance of the widget being built.
9) Optionally (although you always should), override equals(), hashCode(), and toString() methods, etc.

Cons:
1) Can be more verbose than telescoping constructors.
2) Can be a problem in performance-critical situations. (I have never experienced this).
3) - If immutable - you might end up creating a lot of instances over the life of the program.