For my first post here at the prestigious sourJuice I thought I’d serve a little writeup on a generic builder pattern implementation. I hope you enjoy.
Overview
The Builder pattern is often used as a nice fluent way of constructing objects with varying parameters. The drawback is that implementing a builder requires tedious boilerplate code.
An an alternative, several people have proposed utilizing a Proxy to handle builder method invocations against a builder interface. One such implementation I came across recently was by Robbie Vanbrabant.
While I like the idea of using a Proxy to create a generic builder, the implementations I’ve found so far aren’t quite what I’m after. I want a generic builder that can produce objects by invoking setters against my object or by utilizing field reflection, with as little code required as possible. Here is what I came up with.
Implementation
First we’ll define a Builder interface that all specific Builder interfaces must extend.
public interface Builder<T> {
enum BuilderType { FieldBuilder, SetterBuilder };
T build();
}
Next we’ll create our BuilderFactory that produces dynamically created Builder instances based on a provided Builder interface.
Read the rest of this entry »