Builder - C++ Patterns
← Patterns

Builder

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++98 or newer.

Intent

Separate the complex construction of an object from its representation.

Description

The foo class, on lines 3–16, has a complex construction process during which any subset of its properties might be set. This process is captured by the foo::builder class, on lines 18–36. This builder class provides an interface for constructing foo objects, allowing various combinations of parameters to be provided. This avoids having to define a large collection of constructors for foo.

The foo::builder class implements a set of chainable functions for setting the construction parameters (lines 21–24) and a build member function for constructing the foo object with these parameters (lines 26–29).

On lines 40–42, we use foo::builder to construct a foo object, setting its prop1 and prop3 members and calling build to construct the object.

Contributors

  • Joseph Mansfield

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share

Feel like contributing? This website is generated from a git repository. If you have something to add or have noticed a mistake, please fork the project on GitHub.

C++ Patterns created by Joseph Mansfield