Repository navigation
Expand file tree
/
Copy pathsingleton.cpp
More file actions
66 lines (53 loc) · 1.41 KB
/
Copy pathsingleton.cpp
File metadata and controls
66 lines (53 loc) · 1.41 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
// Brandon Robare
// Lab 08
// Singleton Design Pattern Example
// Meyers Singleton
#include <iostream>
#include <fstream>
#include <string>
// singleton ensures only one instance of class exists
// provides a global access point to that instance.
class Logger {
public:
// uses local static variable for lazy instantiation - Meyers Singleton
static Logger& getInstance() {
static Logger instance;
return instance;
}
// report() appends a message to the log file
// payload of singleton
void report(const std::string &msg) {
if (ofs.is_open()) {
ofs << msg << std::endl;
}
}
// singleton cannot be duplicated.
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
private:
std::ofstream ofs;
// only once when getInstance() is first invoked
Logger() {
ofs.open("log.txt", std::fstream::out | std::fstream::app);
if (!ofs) {
std::cerr << "Error: Failed to open log.txt" << std::endl;
}
}
// file is closed when program terminates
~Logger() {
if (ofs.is_open()) {
ofs.close();
}
}
};
// both functions prints message using the same singleton
void functionA() {
Logger::getInstance().report("function A");
}
void functionB() {
Logger::getInstance().report("function B");
}
int main() {
functionA();
functionB();
}