-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuilder.cpp
More file actions
66 lines (57 loc) · 1.64 KB
/
builder.cpp
File metadata and controls
66 lines (57 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/***
Acknowledagement: This is a lecture note for course https://www.udemy.com/course/patterns-cplusplus/ by
@Dmitri Nesteruk
Title: Builder
- Simple objects are simple and can be created in a single constructor call.
- Other objects require a lot of ceremony to create
- Having an object with 10 constructor arguments is not productive
- Instead, opt for piecewise construction
- Builder provides and API for constructing an object step-by-step
When piecewise object construction is complicated, provide an API for doing it succinctly .
Think the HtmlElement as a TreeNode, it has data and a vector of children,
Instead of implementing add_child function inside TreeNode to fill all the children,
we create a builder, keep a treeNode as a member, and add the add_child function there
Shiyu Mou
***/
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <memory>
using namespace std;
struct HtmlElement
{
string name;
string text;
vecotor<HtmlElement> elements;
HtmlElement() {}
HtmlElement(const string& name, const string& text): name(name), text(text){}
string str(int indent = 0) const
{
// some code
// in C++, str is usually for printing
}
};
struct HtmlBuilder
{
HtmlElement root;
HtmlBuilder(string rootname)
{
root.name = root_name;
}
void add_child(string child_name, string child_text)
{
HtmlElement e{child_name, child_text};
root.elements.emplace_back(e);
}
string str() {return root.str();}
};
int main()
{
// easier way
HtmlBuilder builder{ "ul" };
builder.add_child("li", "hello");
builder.add_child("li", "world");
cout << builder.str() << endl;
return 0;
}