Singleton Design Pattern in C++
Hello learners, here we are going to learn a special and important topic that is “Singleton Design Pattern” in C++.
Before diving into the concept directly, let us understand what actually “Singleton Design Pattern” means!
Singleton Design Pattern
Singleton Design Pattern is nothing but a simple design pattern that has a normal class that allows the creation of exactly one object of it and provides global access to the created object.
Now, let us understand this concept in a practical way by implementing it in C++.
Implementation:
step 1: We have to create a class that has its constructor as private so that the user could create only one object.
step 2: The creation of a private static member.
step 3: we have to create a static member function to get an instance.
Example Code:
STEP 1:
Include all the required header files and namespaces.
#include <iostream> using namespace std;
STEP 2:
Create a class named Singleton with required private data members and a private constructor named Singleton(), a public data member function named getInstance() to get the instance of the object, setData() to set the data and getData() to return the data value.
class Singleton { private: static Singleton *inst; int data; Singleton() {} public: static Singleton *getInstance() { if(inst == NULL) { inst = new Singleton(); } return inst; } void setData(int val) { data = val; } int getData() { return data; } };
STEP 3:
Define inst variable with NULL value outside the class and create a main() function and call the getInstance() function and then call the setData() function and print the value using the getData() function.
Singleton *Singleton::inst=NULL; int main() { Singleton::getInstance()->setData(100); cout<<"Data = " << Singleton::getInstance()->getData() << "\n"; }
Output:
Data = 100
Leave a Reply