Finally got a chance to blog about the most recent architectural improvements to ARPool - Singletons! Singletons make so much sense for ARPool it’s insane, I can’t believe we didn’t have it like this before.
Backing up for those who aren’t familiar with what I’m talking about, a singleton is an object for which we enforce the constraint that there will only ever be a single instance of that object. How do we do this? easy make the constructor private, err okay but then how do we instantiate the singleton in the first place? This one isn’t hard but I wouldn’t say easy, we make a public method called getInstance which returns a pointer to the single instance of the class if it has already been initialized or creates it if it has not. The class also has 2 static variables to hold the single instance and a flag indicating whether it has been instantiated yet. The code looks like this:
static bool instanceFlag;
static Singleton* single;
// the rest of the methods...
// cpp file
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
single = new Singleton();
instanceFlag = true;
So why would we want to do this? when is this useful? The best example is whenever you are dealing with hardware or an actual physical element. For example in ARPool there is only one camera so it makes sense to make the camera class a singleton.
The major advantage of using singletons is that you can include the class where ever you like and simply ask for the instance - this can greatly simplify your code because you no longer have to pass all of these objects to each other to access them. A really basic way to think about Singletons is to treat them as safe global objects.
and thats really all there is to it! I’m just going to sit here and smile thinking about how much cleaner ARPool’s code is now mmmmmmmmmmmmm!