The main purpose of a singleton design pattern is that it will ensure a class should have only one instance of it and allow global access to it
When we use a singleton design pattern
Suppose you have a network and many users are using it to print their documents
As you know, a printer is a peripheral device that is slower than computer operations so, it will take little time to print each document
A printer can not print all the documents at a time
For this reason, a printer will have a spooler program that controls the concurrent access to a shared resource
similarly, every network system should have one printer spooler
#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
0
300
300
300
Line 5: a class called singleton is created
Line 14: it will get the instance of class singleton
Line 15:check the instance of the singleton class is created or not suppose if it is not created then it will create a new object of the singleton class
Line 19: if the instance is already created then it will return the instance of the singleton class
Line 34-36: three instances (s,s1,s2) is created of class singleton
Line 38-40: set the data values as 100 for s 200 for s1 and 300 for s2
Observe the output, you might notice that there are three different values were set for s,s1,s2 but the output is the same
Why?
because the singleton class can create only one instance
Leave a Reply