Singleton Design Pattern in C++
Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton pattern is that it provides a global point of access to the class and ensures it has only one instance. Similar to a global variable that can be used everywhere in the program, a singleton object can be used anywhere.
Advnatges of Singleton:
Similar to global variables, singleton has similar advantages and disadvantages.
- Provides control over the object's allocation and destruction.
- This method provides thread-safe access to the global state of an object.
- Pollutes the global namespace by preventing it from being used.
We need a static member, private constructor, and static function in the singleton design pattern class.
Example:
#include <iostream>
using namespace std;
class Singleton {
private:
static Singleton *instance;
int data;
protected:
Singleton() {
data = 0;
}
public:
static Singleton *getInstance() {
if (instance==0){
instance = new Singleton;
}
return instance;
}
int getData() {
return this -> data;
}
void setData(int data) {
this -> data = data;
}
};
Singleton *Singleton::instance = 0;
int main(){
Singleton *s = s->getInstance();
Singleton *s1 = s1->getInstance();
Singleton *s2 = s2->getInstance();
cout << s->getData() << endl;
s->setData(100);
s1->setData(200);
s2->setData(300);
cout << s->getData() << endl;
cout << s1->getData() << endl;
cout << s2->getData() << endl;
return 0;
}
Output:

Explanation:
In the above code, we have created a class called as singleton. In the code, we have created an object for the singleton class by checking that no other object is created for the class. In the code, three instances, s,s1, and s2, are created for the class singleton. We have set the data values as 100 for the s instance and 300 for the s1 instance, and 300 for s2. Here we have set different values, for instance, but the output is similar. This is due to the properties of the singleton design pattern, which is that it can create only one instance for the class