Subclassing with Bloch’s Builder pattern

I love this. I also have a headache now…

Chrononaut

A co-worker of mine recently ran across this post by Eamonn McManus, “Using the builder pattern with subclasses,” and after due consideration, settled on what McManus calls “a shorter, smellier variant.”

Shorter because:

  1. it has only one Builder class per class

Smellier because:

  1. it uses raw types
  2. the builder’s self() method requires an unchecked cast

Frankly, I don’t find the shortness here a compelling argument for the smell, but I also think there’s more shortness to be found in McManus’ design while remaining fragrant. Thus:

 class Shape { private final double opacity; public double getOpacity() { return opacity; } public static abstract class Builder<T extends Shape> { private double opacity; public Builder<T> opacity(double opacity) { this.opacity = opacity; return this; } public abstract T build(); } public static Builder<?> builder() { return new Builder<Shape>() { @Override public Shape build() { return new Shape(this); } }; } protected Shape(Builder<?> builder) {…

View original post 300 more words


One response to “Subclassing with Bloch’s Builder pattern”

  1. David Moles Avatar

    You might be interested in the revised version here, which allows you to call the sub/superclass builder methods in any order: http://chrononaut.org/2013/03/19/subclassing-with-blochs-builder-pattern-revised/

    In some respects it’s not as clean, though.

Leave a comment

Blog at WordPress.com.