-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseExample.cpp
More file actions
78 lines (65 loc) · 1.75 KB
/
DatabaseExample.cpp
File metadata and controls
78 lines (65 loc) · 1.75 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
// Singleton Design Pattern — C++20 Implementation
// Define a class that has only one instance and provides a global point of access to it.
// Standard: C++20
// Build: g++ -std=c++20 -o database DatabaseExample.cpp
#include <format>
#include <iostream>
#include <string>
#include <vector>
class Database
{
private:
std::string host_;
std::string username_;
std::string password_;
std::string database_name_;
// Private constructor so that no objects can be created.
Database()
: host_("localhost"), username_("root"), password_("root"),
database_name_("test")
{
}
// Delete copy and move to prevent duplication
Database(const Database &) = delete;
Database &operator=(const Database &) = delete;
Database(Database &&) = delete;
Database &operator=(Database &&) = delete;
public:
// Meyer's Singleton — thread-safe in C++11+, no raw new/delete
static Database &getInstance()
{
static Database instance;
return instance;
}
// Database operations...
void connect()
{
std::cout << std::format("Connected to {} at {}\n", database_name_, host_);
}
void disconnect()
{
std::cout << std::format("Disconnected from {}\n", database_name_);
}
void executeQuery(const std::string &query)
{
std::cout << std::format("Executing: {}\n", query);
}
std::vector<std::string> getResults() const
{
// Get the results of the last executed query
return {};
}
};
int main()
{
Database &db1 = Database::getInstance();
db1.connect();
db1.disconnect();
Database &db2 = Database::getInstance();
db2.connect();
db2.disconnect();
// Verify it's the same instance
std::cout << std::format("\nSame instance? {}\n",
(&db1 == &db2 ? "Yes" : "No"));
return 0;
}