-
Notifications
You must be signed in to change notification settings - Fork 0
/
Singleton.cpp
98 lines (72 loc) · 1.7 KB
/
Singleton.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
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class Number {
public:
// 2. Define a public static accessors func
static auto Instance()->Number *;
static auto SetType(string t)->void
{
type = t;
delete inst;
inst = nullptr;
}
virtual auto SetValue(int in)->void {
value = in;
}
virtual auto GetValue()->int {
return value;
}
virtual ~Number() = default;
protected:
int value;
// 4. Define all ctors to be protected
Number() : value{0} {
cout << ":ctor: ";
}
// 1. Define a private static attribute
private:
static string type;
static Number *inst;
};
string Number::type = "decimal";
Number *Number::inst = nullptr;
class Octal : public Number {
// 6. Inheritance can be supported
public:
friend class Number;
virtual auto SetValue(int in)->void override
{
char buf[10];
sprintf(buf, "%o", in);
sscanf(buf, "%d", &value);
}
protected:
Octal() {}
public:
virtual ~Octal() override = default;
};
auto Number::Instance()->Number *
{
// 3. Do "lazy initialization" in the accessors function
if (!inst) {
inst = type == "octal"
? new Octal()
: new Number();
}
return inst;
}
auto main(int argc, char *argv[])->int
{
// Number myInstance; - error: cannot access protected constructor
// 5. Clients may only use the accessors function to manipulate the Singleton
Number::Instance()->SetValue(42);
cout << "value is " << Number::Instance()->GetValue() << endl;
Number::SetType("octal");
Number::Instance()->SetValue(64);
cout << "value is " << Number::Instance()->GetValue() << endl;
getchar();
return EXIT_SUCCESS;
}