Search 75,922 tutors
FIND TUTORS

A single ton of singletons!

Singletons can be a beautiful thing. Some don't like using singletons, some do. It's all about your preferences. I, myself, use and abuse them! Well...a singleton CLASS to be exact.

What is a singleton class?
A singleton class is when only one object, or instance, of a class at a time.

How is it useful?
Have you ever had a class that you needed to use throughout a program only once in multiple functions or classes? Chances are there was a time when you messed around with pointers or global objects. Well you're in luck! With a singleton, you can call that class' functions and access its members anywhere in your program, and it will be the same object with the same members throughout! Pretty awesome huh?

That's cool, but what classes would I use it for?
It completely depends on your programming preferences. Some common places I have seen people use singletons in my experience of programming: Application States - these are 'states' of the program. For example, in a game, there's a main menu state, a pause state, an options state, and a game state! There options, the pause, the main menu, and the game are the same no matter when or what time you start the game.

Wrappers - wrappers are, in a way, your own custom helper classes for using seemingly complicated functionality, like APIs. I created a wrapper for DirectX 9.0 (Direct3D) so instead of typing loads of code to set everything up, I can just call D3D->Init(); and everything is done for me behind the scenes. These can be singletons so you don't have to reinitialize everything every time you enter a new part of the program.

There are many more occasions you'll want a singleton, but these are very common examples I see every day.

How Do I Set One Up?
Well, as all programmers know, there's more than one way to skin a cat. The easiest way I've seen it done is with Lazy Instantiation, or Lazy Programming. Why is it called that? See for yourself:

Method 1: Static method

static Function* GetInstance(void)
{
static Function s_Instance;
return &s_Instance
}

Method 2: Memory Allocation method

static Function* s_Instance;

static Function* GetInstance(void)
{
if(s_Instance == nullptr)
s_Instance = new Function;
return s_Instance;
}
static void DeleteInstance(void)
{
delete s_Instance;
s_Instance = nullptr;
}

I felt lazy just typing that. Simple huh?
That's about all I have for singletons. I hope you guys got something out of this :)