AS3 Singletons, the other way
Since you can’t declare a constructor private in AS3, there are a few methods out there to enforce a Singleton. A common way is to declare an internal SingletonEnforcer class outside the package: SingletonEnforcer, but the declaration of the Enforcer outside a package looks a bit “dirty” to me. Another way is to declare the singleton as a static variable, but this way you can’t decide when your singleton is instantiated.
So, why don’t just try nearly same with a local variable:
package { public class Singleton { private static var instance:Singleton; private static const checker:Object = {}; public function Singleton(initObj:Object) { if(initObj != checker) { throw new Error("Private constructor!"); } } public static function getInstance():Singleton { if(instance == null) { instance = new Singleton(checker); } return instance; } } }
Update: I found another nice solution by GSkinner: SingletonDemo.
20. November 2007 | Posted in Actionscript


Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
Trackback this post | Subscribe to the comments via RSS Feed