A small adaptation of the enobrev response is to have an instance as a getter. Some would say that it is more elegant. Also, enobrev's answer will not apply Singleton if you call the constructor before calling getInstance. It may not be perfect, but I checked it and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too).
package { public class Singleton { private static var _instance:Singleton; public function Singleton(enforcer:SingletonEnforcer) { if( !enforcer) { throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" ); } } public static function get instance():Singleton { if(!Singleton._instance) { Singleton._instance = new Singleton(new SingletonEnforcer()); } return Singleton._instance; } } } class SingletonEnforcer{}
Iain source share