It’s been a while since my last post, so let’s take a look at how we
can abuse the Builder pattern in Java and Android!
If you’ve dabbled even just a bit with Android, you’ve probably seen the
builder pattern in action. In short, the pattern consists of a Builder class
which you use to construct an object of another class. For instance in Android
the pattern is used when you create a dialog:
Seems rather simple! The best part is, your builder could provide default
values for properties (e.g. default title text), and you can create multiple
similar objects using the one and same builder. Neat! But wait, how does
this all work under the hood?
Builders VS constructors
Let’s take a simple example: you want a nifty way to create game NPCs. The
NPCs each have a distinct name. Our NPC class could look like this:
So far so good. But wait, our NPCs each have a gender! Let’s add that:
Still manageable. But now we’d like to have height, color of eyes, color of
hair, sexual preference and the favorite color for each NPC. Sigh…
Ehh… Not that nice anymore. So, let’s take a builder to aid us! A basic builder
would look like this:
There’s nothing fancy here yet - just a barebones builder you can use like this:
Nice! But all the NPCs are still the same. Let’s add a way of naming the NPCs:
Do note that the name() method returns the builder itself. This is useful for
method chaining - let’s get back to that in a moment.
Now we can name the NPCs whatever we like:
See where we’re heading? We can now name each NPC how we like! Let’s just do
a small change to our builder and NPC classes - let’s pass the builder as an
argument to the NPC, and let’s also make the builder an inner static class of
Now, if you try to construct an NPC without a builder, you… well, you can’t.
We marked our NPC’s constructor as private, so it can only be called from the
“inside”. Now, the usage changed only slightly:
To wrap it all up, let’s add all the original fields to our NPC and Builder
classes AND let’s make some of the fields have a default value:
Phew! A bit lengthy example, but it really pays off. Let’s have a look at how
we’ll use this newly-introduced builder:
It becomes really easy to adjust the parameters, to create similar objects, and
the creation becomes more legible.
Builders are a neat way of constructing complex objects. They’re an awesome solution
if you ever have a big list of properties you want to define for an object.
For classes with just one or two constructor arguments, you’re better off without
a builder - either create the objects directly or use a static factory method.