Waterproof AS 3.0 Singleton
Friday, November 24th, 2006While 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 {} |
I’ve been reading