The Builder Design Pattern – Sequence Diagram

The Builder design pattern is useful in two cases:

  1. When you want to create a complex object and having one constructor with millions of parameters is not a good option (it NEVER is).
  2. 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:


yUML script:


Flow-wise, the 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 (initStep1(), initStep2, etc..) and when the class is completely initialized, we can request the instance from the builder. Using sequence diagrams:


WebSequenceDiagrams script:

 Builder->-ComplexClass:complexClass = new()
 Builder->-ComplexClass:step 1 initializations
 Builder->-ComplexClass:step 2 initializations

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.

Enhanced by Zemanta

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.