Author image

Builder Design Pattern


Difficulty:
1/5


An introduction to the important Builder design pattern. There is a nice example to make you go from Zero-to-Hero fast with this pattern!

The Builder pattern is designed to provide a flexible solution to various object creation problems in oop. We intend to separate the construction of a complex object from its representation.

Advantages

It provides control over the individual steps in the object construction process st we can better customize object representation. The benefits of the builder design pattern really shine when we have big complicated classes.

Disadvantages

It requires a separate Builder class for each type of such complex object and it makes dependency injection harder to work with since introducing many dependencies can get things out of hand.

Also it increases code size and almost doubles the amount of memory required since almost all variables (except possibly those with some default values and constants) have to be duplicated in the nested Builder class.

Design

  • create your target big/complex class you want to generate objects
  • create a nested class called Builder.
  • The Builder class contains:
    • the state data required to build the object, which means many of the data contained in the outer/target class (if not more for data needed by other interacting classes with the Complex class)
    • setter functions for each data member of the Builder class, which are called to customize the properties of our Complex object. They all return a reference to Builder& such that we can chain multiple of them nice and easily when we create the object
    • a create method returning the Object created in that return statement back to the caller

Usage

Create your Builder object like so:

auto myComplexClass = ComplexClass::Builder{}
    .setX(1)
    .setY(2)
    .setZ(3)
    .setName("Key")
    .setColor("Black")
    .set...()
    . ...
    .create();

Notice that each getter/setter returns a reference to the Builder so we can use function chaining to our advantage. The create() function goes last and takes no arguments.

I used Windows 8.1 x86_64, Visual Studio 2017, C++17 to build the project.

Github

Github repository link.


0 likes