Safely reusing Singleton classes in multi-instance apps
March 8th, 2010 Posted in AS3, General | No Comments »Wisdom seems to have it that in general Singletons are mostly bad. The actual usecase where you need “one and only one” instance in an application are few are far between. The web is awash with opinion about the pros and cons of using Signletons, that is not my aim here.
This post is aimed at anyone who has built up a library of code over a number of projects and have some useful logic wrapped up in Sinlgeton classes which are being used as the only instance in those apps.
I have a particular Singleton that I have used in quite a few apps and its always been the case that one instance per app is exactly what I needed. In a new project I’m working on I released that I’d like to use the class, but I have clear divisions in my app that would logically take one instance of their own of the class curretly wrapped by the Singleton pattern.
My options here were:
- Option A: Rewrite the class as a non-Singleton and face having to refactor my other applications to work with the new way when I come to make a new release.
- Option B: Duplicate the logic into another non-Singleton class so I dont break the compiles of my other apps.
- Option C: None of the above.
Option A is a pain but at least I could address compile issues on a per case basis when I make new builds, though it will be a somewhat tedious process, and in some cases I actually really do want “one and only one” so the Singleton really makes sense. Option B, would grate… seriously, I would continue to feel sullied until the situation was rectified
So onto Option C. A very simple idea occured to me. What if my Singleton’s default behaviour was to return the one and only instance, but the class could be updated to generate more than one named instance if required. This way all my old apps would go on using the Singleton instance and my new app could instantiate the multiple named instances required without breaking things or duplicating code.
Heres an example:
As you can see the default behaviour of the getInstance() method is to return the Singleton instance, but now the class will also maintain a hash map of other named instances requested via the optional identifier parameter. The class now become something of a self instantiating Factory, but still encapsulates access to the instances.
