Return to Snippet

Revision: 19815
at October 31, 2009 17:56 by chrisaiv


Initial Code
package
{
	public class Singleton
	{
		private static var _instance:Singleton;
		private static var _okToCreate:Boolean = false;
		
		public function Singleton()
		{
			if( !_okToCreate ){
				throw new Error("Error: " + this + 
					" is not a singleton and must be " + 
					"accessed with the getInstance() method");				
			}
		}
		
		public static function getInstance():Singleton
		{
			if( !Singleton._instance ){
				_okToCreate = true;
				_instance = new Singleton();
				_okToCreate = false;
			}
			return _instance;
		}
	}
}

Initial URL

                                

Initial Description
There are a variety of ways to create a Singleton in AS3 but because Adobe wants to be ECMA compliant, there's no way to do it (like in Java) using a private constructor.  Writing a singleton this way will give you a runtime warning if something goes wrong.

Initial Title
AS3: My favorite example of Singleton

Initial Tags

                                

Initial Language
ActionScript 3