In software engineering, Creational Design Patterns deal with object creation mechanisms — trying to create objects in a manner suitable to the situation. The basic or ordinary form of object creation could result in design problems or added complexity to the design. Builder Design Pattern in C++ solves this specific problem by separating the construction of a complex object from its representation.
The code snippets you see throughout this series of articles are simplified, not sophisticated. So you often see me not using keywords like override
, final
, public
(while inheritance), just to make code compact and consumable(most of the time) in single standard screen size. I also prefer struct
instead of class
just to save a line by not writing “public:
” sometimes and also miss virtual destructor, constructor, copy constructor, prefix std::
, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible, rather than the standard way based on common jargon.
Note:
To create/instantiate complex & complicated object piecewise & succinctly by providing an API in a separate entity.
Suppose you have to create the HTML generator using C++ then very naïve way to do it is :
C++
// <p>hello</p>
auto text = "hello";
string output;
output += "<p>";
output += text;
output += "</p>";
printf("<p>%s</p>", text);
// <ul><li>hello</li><li>world</li></ul>
string words[] = {"hello", "world"};
ostringstream oss;
oss << "<ul>";
for (auto w : words)
oss << " <li>" << w << "</li>";
oss << "</ul>";
printf(oss.str().c_str());
A sophisticated dev will create a class with a bunch of constructor argument and method to add a child node. This is a good approach though but it may complicate the object representation.
In general, some objects are simple & can be created in a single constructor call while other objects require a lot of ceremonies to create.
Having an object with 10 constructor arguments is not productive. Instead, we should opt for piecewise construction.
Builder provides an API for constructing an object step-by-step without revealing actual object representation.
#cpp #design pattens #cpp17 #cpp11 #cplusplus #programming-c