Creational Design Patterns
Creational design patterns focus on how objects are created and initialized. They provide mechanisms for creating objects without specifying the exact class of object that will be created.
Singleton
The Singleton pattern ensures that there is only one instance of a class and provides global access to that instance. This pattern is often used in scenarios where there is a need for a single point of access to a shared resource or an object that controls a system-wide behavior.
In the example code below, we implement a Singleton class that allows only one instance of the class to be created. The getInstance()
method is used to retrieve the instance of the Singleton class, and the showMessage()
method is called to display a message from the Singleton instance.
1#include <iostream>
2
3using namespace std;
4
5// Singleton class
6// ... (see code field for the full code snippet)
7
8int main() {
9 // Get the singleton instance
10 Singleton* singleton = Singleton::getInstance();
11 // Show message
12 singleton->showMessage();
13
14 return 0;
15}
xxxxxxxxxx
}
using namespace std;
// Singleton class
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
// Get the singleton instance
static Singleton* getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
void showMessage() {
cout << "Hello from Singleton!" << endl;
}
};
// Initialize static instance
Singleton* Singleton::instance = nullptr;
int main() {
// Get the singleton instance