There are many circumstances where we need a way to globally access data without having to pass pointers almost everywhere. The singleton pattern provides a global access point to some class and it can ensure that only one instance (or some other fixed number of instances) exists in the whole application. As an example, you may want to access a class or structure holding application-wide preferences from within various classes. A classic solution is to have constructors taking a pointer to that class. A cleaner solution involves a singleton class.
Althought there may be different ways to implement a singleton class, here is a simple C++ example. It ensures only one instance of our singleton class is created. Both class declaration and implementation are quite self-explanatory.
The class implementation would look like this:
Looking at the example code, you will see that there are only two unusual things: a pointer to a static instance
of our singleton class (this ensures we only have one application-wide instance) and a private constructor (this
ensures users cannot instantiate the class directly). Using a static pointer in place of a static object to handle
the global instance makes our class more robust, as some compilers fail to call the constructor for static objects,
especially in libraries.
Again, this is just a simple example. The pattern can be adapted and extended to best fit to your needs.