Skip to content

Commit 20dfc1b

Browse files
authored
Merge pull request #23 from urboob21/dev_branch
id 1763992259
2 parents 78a75b0 + 986879c commit 20dfc1b

3 files changed

Lines changed: 92 additions & 0 deletions

File tree

CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ set(APP_SOURCES
108108
"src/patterns/behavioral/Strategy.cpp"
109109
"src/patterns/behavioral/State.cpp"
110110
"src/patterns/behavioral/Observer.cpp"
111+
"src/patterns/creational/Singleton.cpp"
111112
)
112113

113114
# Test files

docs/uml/patterns_creational_singleton.drawio.svg

Lines changed: 4 additions & 0 deletions
Loading
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// cppcheck-suppress-file [functionStatic]
2+
3+
// Singleton is a creational design pattern that lets you ensure that a class has only one instance,
4+
// while providing a global access point to this instance.
5+
// Appicability:
6+
// (*) when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program.
7+
// (**) when you need stricter control over global variables.
8+
9+
#include <iostream>
10+
11+
namespace
12+
{
13+
namespace SingletonPattern
14+
{
15+
16+
/**
17+
* The Singleton class defines the `GetInstance` method that serves as an
18+
* alternative to constructor and lets clients access the same instance of this
19+
* class over and over.
20+
*/
21+
class Singleton
22+
{
23+
private:
24+
static inline Singleton *instance = nullptr;
25+
static inline int num = 0;
26+
/**
27+
* The Singleton's constructor should always be private to prevent direct
28+
* construction calls with the `new` operator.
29+
*/
30+
Singleton() = default;
31+
32+
public:
33+
// 1. Should not be cloneable.
34+
Singleton(const Singleton &other) = delete;
35+
36+
// 2. Should not be assignable
37+
Singleton &operator=(const Singleton &other) = delete;
38+
39+
static Singleton *getInstance()
40+
{
41+
if (instance == nullptr)
42+
{
43+
instance = new Singleton();
44+
num++;
45+
}
46+
47+
return instance;
48+
}
49+
50+
void operation() const
51+
{
52+
std::cout << "Singleton operating num:" << num << "\n";
53+
}
54+
};
55+
56+
namespace Client
57+
{
58+
void clientCode(const Singleton *const s)
59+
{
60+
s->operation();
61+
}
62+
}
63+
64+
void run()
65+
{
66+
const Singleton *s1 = Singleton::getInstance();
67+
Client::clientCode(s1);
68+
69+
const Singleton *s2 = Singleton::getInstance();
70+
Client::clientCode(s2);
71+
72+
// Singleton* s3 = new Singleton(); // ERROR
73+
}
74+
75+
}
76+
}
77+
78+
struct SingletonAutoRuner
79+
{
80+
SingletonAutoRuner()
81+
{
82+
std::cout << "\n--- Singleton Pattern Example ---\n";
83+
SingletonPattern::run();
84+
}
85+
};
86+
87+
static SingletonAutoRuner instance;

0 commit comments

Comments
 (0)