Actionscript 3.0 and Singletons
Yesterday my friend Lord Singleton had to come over and we talked about a couple of variations of his dance.
The problem with Singletons is that they require a private constructor and as 3.0 doesn’t support that. So obviously you need a workaround. Here’s two that you could use.
Solution number 1 (AKA the best)
public class Singleton { private static var _instance:Singleton = null; public function Singleton(enforcer:SingletonEnforcer) { } public static function getInstance():Singleton { if(_instance == null) { _instance = new Singleton(new SingletonEnforcer()); } return _instance; } } class SingletonEnforcer {};
Solution number one uses a class instance inside the Singleton class (outside of the parentheses) and so the constructor can’t be called from outside without generating an error (which is what a Singleton is all about, we only want 1 instance of a Singleton class).
Solution number 2 (AKA the funkiest)
public class Singleton { private static var _instance:Singleton = null; private static var secret:Number = Math.random(); public function Singleton(enforceNumber:Number) { if (enforceNumber != secret) { throw new Error("This class is a Singleton"); } } public static function get instance():Singleton { if (_instance == null) { _instance = new Singleton(secret); } return _instance; } }
By doing it this way you let the Singleton class generate a secret number (oooh secret!) so you can’t make a new instance without generating an error (because only the class knows what number it generates).
Isn’t this extremely funky? On top of that I heard that the lead singer of Kool and the Gang does it like this, too!
