RegExr v2: Build, Test, & Lear…
A Meandering Path to an Evolvi…Quick as a FlashThings Every ActionScript Deve…Making Money with Adobe AIRUsing Flash for 3D Game MMO UIUtilizing Flash for Game UI De…Why I (Still) Love FlashMy Favourite Things
Posted on July 12, 2006 by Grant Skinner
In ActionScript 3, class constructors can only be set to public. Adobe has stated that this is because the ECMAScript specification is not yet complete, and they did not want to break forwards compatibility with the specification. This makes a lot of sense, but it leaves AS3 developers without a clear way to implement the Singleton design pattern. Luckily, there are a couple ways of faking Singleton functionality. Both solutions are kind of hack-ish, but they get the job done.
My first idea was to use errors to control instantiation:
This approach works very well and the implementation seems relatively clean to me. It will throw a run-time error if you try to instantiate the class directly, and will return null if you use try/catch to circumvent the error. The main disadvantage is that it does not generate compile time errors.
Claus Wahlers pointed me to another approach that was documented on the Kiwi Project blog. This approach takes advantage of the fact that you can define private classes outside of the package declaration, and use them as a “key” to control instantiation.
This second solution feels a little more hackish to me, and I’m not completely certain whether this private class feature is officially supported. However, if you need compile-time errors, it’s the way to go.
Both solutions also break down if you try to extend the class, as the constructor will be called when the subclass is instantiated. Extending Singletons is fairly rare, but if you need to do it, I’d recommend modifying the first solution (the second solution simply won’t work for inheritance).
Follow @gskinner on Twitter for more news and views on interactive media.