Builder design pattern is useful in two cases:
- When you want to create a complex object and having one constructor with millions of parameters is not a good option (it NEVER is).
- When you want to abstract the way an object is created by using different builders depending on the required task.
These are actually two very different needs. I will focus on the first type of builder, because the second kind of builder is very similar to an Factory.
In a class diagram, a builder looks like this:
[Client]->[Builder] [Builder|createNewInstance();initStep1();initStep2();getInstance():ComplexClass] [Builder]->[ComplexClass]
Builder works like this: first, we tell it that we want to build a new
ComplexClass, maybe passing some initial parameters. Then we call all the steps required to build that class (
initStep2, etc..) and when the class is completely initialized, we can request the instance from the builder. Using sequence diagrams:
Client->+Builder:createNewInstance() Builder->-ComplexClass:complexClass = new() Client->+Builder:initStep1() Builder->-ComplexClass:step 1 initializations Client->+Builder:initStep2() Builder->-ComplexClass:step 2 initializations Client->+Builder:getInstance() Builder-->-Client:complexClass
I don’t specify what is done in the initialization steps called by the
Builder. This is the actual work that the
Builder abstracts from the client. It can be a simple method call or a long set of operations, but to the client this is irrelevant.
Last week I read about something called the
Wizard design pattern, which seems an improved version of the
Builder pattern. I will dig into it and post about soon.