Thursday, December 16, 2010

Notes on the Builder Pattern

This post simply describes the Builder Pattern, for my own future reference. This pattern is useful in constructing immutable objects that have numerous properties, some required and some optional, without using numerous constructors to support various permutations. And, of course, since the object is immutable, there are no setters or non-private fields to support post-construction alterations. With the Builder pattern, one can ensure objects are not only immutable, but have completed state initialization before use.

Here's the overview idea:

  1. Provide no setters or non-private fields to alter any of its properties, but do provide getters as needed.
  2. Provide a public static inner class that will act as the "builder", with one constructor that accepts all required arguments for the class (i.e. those properties which must be set at a minimum).
  3. The builder duplicates all properties supported by the target class.
  4. The builder provides public "setters" that set values for these properties - and returns itself (that's why I'm quoting "setters" - this is a variation on the normal JavaBean setter idiom).
  5. The target class provide one private constructor which accepts the builder as its sole argument.
  6. The builder provides a "build it" method that invokes that private constructor with itself.
  7. Finally, the target class constructor assigns each of its fields from the corresponding field in the builder.

Usage goes like this, for a target class Target that implements TargetIntfc:


TargetIntfc t = new Target.Builder(Required value).setOption1(value1).setOption2(value2).build();

As far as a more in-depth discussion, Joshua Bloch does a much better job than I ever will, so I defer to him.

No comments:

Post a Comment