Subclassing with Bloch’s Builder pattern

Posted: 5 November 2014 in Teamsite

I love this. I also have a headache now…


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

  1. David Moles says:

    You might be interested in the revised version here, which allows you to call the sub/superclass builder methods in any order:

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s