Author image

Builder Design Pattern


Difficulty:
1/5


An introduction to the Builder software design pattern, along with a fancy example you will go from Zero-to-Hero in no time, 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 such that 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
  • your target class has properties/member-variables as data. You can choose whether or not you want to provide setters/getters for them. For the sake of this example I didn't, but you totally can.
  • create a nested class in it called Builder
  • The Builder class contains:
    • a default constructor - we specify its data through setter functions (more on that later)
    • 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 classes interacting with the target class)
    • setters for each data member of the Builder class, which are called to customize the properties of our target class object. They all return a reference to Builder& such that we can chain multiple of them nice and easy when we create the object
    • Builder doesn't need any getters
    • alternatively you could best get rid of all setter functions in Builder & pack them all into a public data struct which you provide on create
    • 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