Waterproof AS 3.0 Singleton
While reading Advanced ActionScript 3 with Design Patterns I’ve once again came across the AS 3.0 Singleton solution that has to deal with the absence of private constructors (I’ll save my rage and cursings about who had the idea to remove them for now
) and while the authors are using the already well known method of using a SingletonEnforcer class outside the Singleton’s package to verify that the class cannot be instanciated via the constructor they also note that this can be doublecrossed by giving null or undefined as a constructor parameter. As this is rather sub optimal I was wondering why they don’t just check inside the Singleton constructor for a null/undefined argument and throw an exception accordingly?!
I’m sure somebody else had the same idea already but here’s my idea of a waterproof Singleton class that cannot be misused from the outside (As always, if I missed any detail that accidentally breaks hell loose feel free to correct me) …
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package { public class WaterproofSingleton { static private var _instance:Singleton; public function Singleton(singletonEnforcer:SingletonEnforcer) { if ((singletonEnforcer as SingletonEnforcer) == null) { throw (new Error("Direct instantiation of a Singleton is not allowed!")); } } public static function getInstance():Singleton { if (Singleton._instance == null) { Singleton._instance = new Singleton(new SingletonEnforcer()); } return Singleton._instance; } } } class SingletonEnforcer {} |

The ideal solution would throw a compiler error, not just a runtime exception. I think that’s why they decided to forego checking the argument.
Yes but we don’t have the compile time checking so it’s still better to have a runtime exception than having nothing, isn’t it?
For some additional thoughts on the singleton pattern, I collected them here.
Keith, is right. We left out the condition that checks for the null value simply because it doesn’t throw a compiler error. But if you’re cool with just having a runtime error then by all means feel free to add the condition.
Danny … cool! One of the authors here! I guess I’m taking it too serious with the Singleton!
btw when will you guys upload the source codes for the book?!?
We’re working on gathering and posting the code now. Check the site in a couple weeks.