To continue from the first part, let’s see how we can extend the functionality
of an existing builder.
Let’s take a simple builder for an example tha builds a NPC object:
While counter-intuitive for such a simple use case, this will be our basic
builder. Now, let’s see how we’ll extend on this!
Extends… or does it?
Let’s create a new class we want to build. This class will be called Guard
and it’ll extend from NPC.
It almost works, but not quite. Our NPC.Builder does not have the strength
field. Hmm… Maybe we should create a builder for Guard that extends from
Oooo-kay, seems to work. Let’s see the usage:
Okay, this works too! Great! Let’s create another Guard:
Errr. This doesn’t work! If you tried this in your editor, you probably got
and error saying “incompatible types”. What’s going on?
Types And Builders
The reason the last bit of code didn’t work is that when we called name() to
set the guard’s name, we left the scope of the Guard.Builder and started working
on the NPC.Builder, which has no idea that the Guard class even exists.
Similarly, if you tried to set the name first, you wouldn’t be able to set the
guard’s strength anymore - not that it matters at all since we can’t construct
a guard anyway.
But wait! We can use generics to achieve what we wanted! For this, we have to
create a new abstract builder which takes two type arguments: First type B denotes
the type of the builder, and the second type T denotes the type of the object
the builder creates. The abstract builder looks like this:
Next, we make the NPC.Builder extend AbstractBuilder:
And finally, let’s make the Guard.Builder extend the NPC.Builder:
Great! Now we can use the builders just as we like:
By extending builders, we can create really complex builder hierarchies and
many different types of resulting objects. The usage of the builders is still
as easy as always - we just introduce new functionality by extending the old