Skip to content

Builder

Roberto Fronteddu edited this page Jan 26, 2023 · 9 revisions

The Builder is a Creational Design Pattern. A Builder delegates the construction of an object to a class that separates the process into multiple steps.

Usefull when/Problems that this pattern tries to solve

  • Creating immutable classes can be confusing with just a constructor (because it may have several parameters sharing the same type leading to bugs such as passing parameters in the wrong order)
  • Simplify the process of initialization
  • We have a complex construction process of an object involving multiple steps
  • A Builder removes the logic related to object construction from the client code and abstracts it in separate classes.

Example

builder-uml

  • Product: Final complex object that we want to create using the builder
  • Builder: Defines methods (i.e. provide an interface) to build parts of our complex object. The Builder provides also a method to assemble the object called build()
  • ConcreteBuilder: Implements the Builder class.
  • Director: Provides the logic to call the Builder methods in the right order

Considerations

  • An immutable class can be created by implementing a builder as a static inner class (only the builder will then be able to access private methods to modify and create the class)
  • The director role is rarely implemented as a separate class, typically the consumer of the object instance or the client handles that role
  • Abstract builder is rarely implemented if the product itself is not part of any inheritance hierarchy.

Comparison with prototype

Builder:

  • We have a complex constructor and a builder allows us to work with that.
  • We can create the builder as a separate class, this can be used to work with legacy code.

Prototype:

  • Prototype allows us to not use the constructor.
  • In JAVA, we use the clone method and we need to modify existing code so it may not work with legacy code.

Implementation Steps:

  1. Create the Builder
    • Identify the parts of the product and provide methods to create those parts.
    • Provide a method to assemble or build the product/object
    • Provide a method to get a fully built object out (optionally, the builder can keep a reference to a product it had built)
  2. A Director can be a separate class or the client can play this role.

Real-Life Example:

StringBuilder: The StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Clone this wiki locally