Design Patterns: Singleton
Updated: Jul 12, 2021
Have you ever had one of those moments where you need to have just one instance of an object and pass it around. Like a Frisbee? Well then the singleton pattern is the right one to use. It is an object where, yeah I've already explained. One and only one instance, come on keep up. I mean there nothing stopping you from creating multiples, but... you'd be wasting computational time. So... score one for great design. Now... inside of this pattern there are a few different ways of constructing it each one a little more difficult to remember and with different usages.
Here is a diagram of how it all fit's in together:
The very first thing that we need to do is to create an interface to abstract our object. Again we are doing this for dependency injection reasons.
I'll cover that topic in a later post, just know it's amazing. Use it anytime it is applicable. Seriously... do it.
Great super, excellent. We did it and implemented the interface, aren't we great. Finished, right ?!
Well no... not yet. There is more text after this, come on now.
Our next step is to turn this normal everyday class into a singleton. We do this by creating an instance of out MySingleton class inside of our MySingleton class (Singletonception...). This makes sure that there can only ever be one instance of this object as static objects point back to the same reference point in memory.
WOW!! Big changes essentially by creating an instance of a static object we have. Wait for it... we made sure that there is only one instance of the object. We can now call MySingleton.Instance to essential pass around the object. Neat! But... we can be lazy, like super, actually implement a lazy loading object. Basically what we have done with creating an instance of a static object is created an object way, way before we may need it. Program executes... baam, object created. This is less than ideal, so we are going to be lazy about it (pun intended).
By creating the object lazily we have said that when, we first need the object create it. Instead of you know, at the start. When no-one needs it. At all. Full stop.
The line "static Lazy<MySingleton> instance = new Lazy<MySingleton>(
() => new MySingleton());" looks scary but, essential all that we are doing is creating a new lazy object of type MySingleton and then when instance first gets
called, create a new instance of MySingleton.
And there you have it. A lazy loading singleton, imagine the implications. See... I told you that it was going to be an exciting post. kinda...
I really need to work on my post finishers...