-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path103 Builder Pattern.cpp
110 lines (85 loc) · 1.92 KB
/
103 Builder Pattern.cpp
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
102
103
104
105
106
107
108
109
110
#include <string>
/*
class Person
{
std::string name_{};
int age_{};
std::string name_temp{};
int age_temp{};
public:
explicit Person() = default;
Person& age(int age)
{
age_temp = age;
return *this;
}
Person& name(const std::string& name)
{
name_temp = name;
return *this;
}
Person& builder()
{
name_ = name_temp;
age_ = age_temp;
return *this;
}
};
//@CLK
int main1()
{
Person* p = new Person;
p->age(20).name("Arthur").builder();
}
*/
#include <iostream>
#include <string>
#include <memory> // For std::unique_ptr
#include <execution>
class Person
{
std::string name_;
int age_;
// Private constructor to restrict direct instantiation
explicit Person(const std::string& name, int age) : name_(name), age_(age) {}
public:
// Nested Builder class
class Builder
{
std::string name_temp{};
int age_temp{0};
public:
Builder& age(int age)
{
age_temp = age;
return *this;
}
Builder& name(const std::string& name)
{
name_temp = name;
return *this;
}
std::unique_ptr<Person> unique_ptr()
{
if (name_temp.empty() || age_temp == 0) throw std::exception("values not set correctly");
return std::make_unique<Person>(name_temp, age_temp);
}
Person build() const
{
return Person(name_temp, age_temp);
}
};
// Display method for testing
void display() const
{
std::cout << "Name: " << name_ << ", Age: " << age_ << std::endl;
}
};
// Main function demonstrating the Builder Pattern
int main()
{
// Use the Builder to create a Person object
auto p = Person::Builder().age(20).name("Arthur").unique_ptr();
p->display(); // Output: Name: Arthur, Age: 20
return 0;
}