Learning C++ and OO methodology has been fun, the semester is nearly done, and I had learned whole bunch of interesting thing. One of the base thing that we learned this semester when talking about OOP was function permissions, functions can be public, private and protected, and we all know that a class constructor has to be public, right? Otherwise, how are you going to instantiate the class? You want to see an example of private constructor? Enter a Singleton Pattern:
What is a Singleton – a singleton is a way to create your object where instead of instantiating an object, you get an instance of the object that has been previously created. If the instance does not exist, then the instance will be created, but check out following code:
#include
using namespace std;
class Singleton {
private:
bool CanIHazAnInstance;
static Singleton *single;
//private constructor – could this be????
Singleton()
{
}
public:
//this is a weird function, it will be called BEFORE constructor
static Singleton* getInstance();
void MySuperCoolFunction();
~Singleton()
{
CanIHazAnInstance = false;
}
};
bool Singleton::CanIHazAnInstance = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
//this is where magic happens:
if(!CanIHazAnInstance)
{
//if there is no instance as of yet,
//we will call our private constructor
single = new Singleton();
//and set our instance flag to true, so we know
//that an object has been instantiated.
CanIHazAnInstance = true;
return single;
}
return single;
}
}
void Singleton::MySuperCoolFunction()
{
cout << "SuperCoolFunction is Super Cool!!!" <MySuperCoolFunction();
//Over here, the instance has already been created, so this
//time, we won’t have to call constructor
single2 = Singleton::getInstance();
//Oh, look here is that SuperCoolFunction again!!!
single2->MySuperCoolFunction();
return 0;
}
Now, I know, the example is kind of weak, I mean that SuperCoolFunction just outputs some stuff to the screen, right? So you might ask yourself – where would I possibly use an approach like this? Consider following scenario – you are writing an application of some sort. This application has options, like let’s say default fonts, colors and so on. As we can imagine, we will have to keep those options somewhere in the file and to access those we need to open the file, read it, and close it. Even worse if you have to modify those options at some point. Using a handy Singleton Pattern, we have one instance of options for our application loaded and available to all objects that might require it.