-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathConceptualExample01.cpp
More file actions
101 lines (80 loc) · 2.4 KB
/
ConceptualExample01.cpp
File metadata and controls
101 lines (80 loc) · 2.4 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// ===========================================================================
// ConceptualExample01.cpp // Builder Pattern
// ===========================================================================
#include <iostream>
#include <iomanip>
#include <string>
#include <list>
#include <memory>
namespace ConceptualExampleBuilder01 {
class Product
{
private:
std::list<std::string> m_parts;
public:
void add(const std::string& part) {
m_parts.push_back(part);
}
void show() {
std::cout << "Parts:" << std::endl;
for (const auto& part : m_parts) {
std::cout << std::setw(10) << part << std::endl;
}
}
};
class Builder
{
public:
virtual ~Builder() {}
virtual void buildPartA() = 0;
virtual void buildPartB() = 0;
virtual std::shared_ptr<Product> getProduct() = 0;
};
class Director
{
public:
void construct(std::shared_ptr<Builder>& builder)
{
builder->buildPartA();
builder->buildPartB();
}
};
class ConcreteBuilder : public Builder
{
private:
std::shared_ptr<Product> m_product;
public:
ConcreteBuilder()
: m_product{ std::make_shared<Product>() }
{}
virtual ~ConcreteBuilder() {}
void buildPartA() override {
m_product->add("Part A");
}
void buildPartB() override {
m_product->add("Part B");
}
std::shared_ptr<Product> getProduct() override {
return std::move(m_product);
}
};
static void clientCode(Director& director)
{
// 'Product' is created through the builder - here: ConcreteBuilder
std::shared_ptr<Builder> builder{ std::make_shared<ConcreteBuilder>() };
// the builder is handed over to the director - including the product
director.construct(builder);
std::shared_ptr<Product> product{ builder->getProduct() };
product->show();
}
}
// function prototypes
void test_conceptual_example_01()
{
using namespace ConceptualExampleBuilder01;
Director director;
clientCode(director);
}
// ===========================================================================
// End-of-File
// ===========================================================================