-
Notifications
You must be signed in to change notification settings - Fork 0
/
lazy_init.cpp
55 lines (43 loc) · 1.2 KB
/
lazy_init.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
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Fruit {
public:
static Fruit* GetFruit(const string& type);
static void PrintCurrentTypes();
private:
// Note: constructor private forcing one to use static |GetFruit|.
Fruit(const string& type) : type_(type) {}
static map<string, Fruit*> types;
string type_;
};
// static
map<string, Fruit*> Fruit::types;
// Lazy Factory method, gets the |Fruit| instance associated with a certain
// |type|. Creates new ones as needed.
Fruit* Fruit::GetFruit(const string& type) {
auto [it, inserted] = types.emplace(type, nullptr);
if (inserted) {
it->second = new Fruit(type);
}
return it->second;
}
// For example purposes to see pattern in action.
void Fruit::PrintCurrentTypes() {
cout << "Number of instances made = " << types.size() << endl;
for (const auto& [type, fruit] : types) {
cout << type << endl;
}
cout << endl;
}
int main() {
Fruit::GetFruit("Banana");
Fruit::PrintCurrentTypes();
Fruit::GetFruit("Apple");
Fruit::PrintCurrentTypes();
// Returns pre-existing instance from first time |Fruit| with "Banana" was
// created.
Fruit::GetFruit("Banana");
Fruit::PrintCurrentTypes();
}