9 de enero de 2014

Builder Pattern in Java, by an example.

This is an example of the builder pattern. To copy, paste, run, learn, whatever.

Warning
It's supposed you already know why you want to use the Builder pattern, its benefits, cons, etc..

Right now, the example



What did we do?

We needed a class with some properties (of course!) and another class for building it.

1-TheClass

TheClass must have a private constructor, accepting a Builder object as argument

2-Builder

Builder, an inner public static class named Builder(or as you like), with same properties as TheClass.
Builder properties can have default values.
Builder must have a public constructor accepting as arguments all the required properties of TheClass.

3-Methods

Set methods are in Builder class for filling the optional properties of TheClass.
Those methods returns "this" i.e. a Builder object so allowing calls to be chained, like setThis(x).setThat(y).setThose(z)
Finally to create TheClass object, the cherry on top is a build() method, using new internally, and returning it. The body of build() is:
TheClass build(){ return new TheClass(this);}

4-Test it!: Creating a TheClass object

Get a static Builder(with required arguments), set optional properties(chained), and build()!


Further Reading
Some links for those who prefer reading over trying and clicking over googling.
Builder Patterns explained by Joshua Bloch
StackOverflow:Builder Pattern
StackOverflow: Method chaining - why is it a good practice, or not?