Let's know what is Singletons :
Sometimes we need to have only one instance of our class for example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly. Similarly, there can be a single configuration manager or error manager in an application that handles all problems instead of creating multiple managers and hence , Singletons comes ;
Definition :
The singleton pattern is a design pattern that restricts the instantiation of a class to one object.
Simple Implementation :
#include "iostream"
class Singleton{
public:
Singleton(const Singleton& ) = delete ; // Singletons should not be cloneable.
static Singleton& getInstance(){
return s_instance;
};
private:
Singleton(){};
static Singleton s_instance;
};
Singleton Singleton::s_instance;
int main(){
auto& ins = Singleton::getInstance();
return 0;
};
A Simple Example based on Singletons :
#include "iostream"
class Random{
public:
Random(const Random& ) = delete ;
static Random& getInstance(){
static Random s_instance;
return s_instance;
};
static float Float(){ return getInstance().IFloat(); };
private:
Random(){};
float IFloat(){ return getRandom; };
float getRandom = 0.5f;
};
int main(){
auto random = Random::Float();
std::cout << random;
return 0;
};