The idea of a singleton is that you can have one and only one object of that class.
To prevent you from creating objects directly, all the constructors are private. Since the constructors are private, you have no way of directly creating an object.
A public static member (Instance()) is provided for this. Instance makes sure to create the object once. and returns a reference to it. Any further calls to instance and it just returns a reference to the same object, so every client is referring to the same single object.
// Why Put Static in Here? |
remember how static works in functions - it means that variable declared static only gets initialised the first time the function is called, and it retains it's value between function calls. So the first time Instance() is called, it creates instance and returns a reference. Next time Instance() is called, instance already exists and is not modified, it just returns the reference.
The more common alternative to this is to have a member variable which is checked and initialised once, see if you can compare the two and see that they're achieving the same thing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
class Singleton
{
Singleton() {};
Singleton(const Singleton &);
Singleton operator(const Singleton &);
public:
static Singleton *pInstance;
static Singleton *Instance();
};
Singleton *Singleton::pInstance = 0;
Singleton *Singleton::Instance()
{
if (!pInstance)
{
pInstance = new Singleton;
}
return pInstance;
}
|
This forces you to have that pInstance, even if it's just a nullptr, regardless of whether you use it or not. Also the previous version lets you return a reference rather than a pointer, so you can't accidentally abuse it the way we often do with pointers.
How could the GetString() and SetString() methods be used? |
1 2 3 4 5
|
string ss = StringSingleton::Instance().GetString();
StringSingleton::Instance().SetString("ss");
StringSingleton sing = StringSingleton::Instance();
sing.SetString("ssss");
string ss2 = sing.GetString();
|