Implement the Singleton In AS3

Implement the Singleton In AS3

The following example implement the Singleton In AS3 at the run-time.I don’t know if there is some other way to implement the Singleton in Compile-time.

 

From http://www.tink.ws/blog/stricter-singletons/

Strict Singletons in AS 3.0

With As 3.0 conforming to ECMA there you can no longer have private constructors which makes creating strict singletons a little bit more tricky. If I write a singleton, I want it written in a way that only a single instance can be created and if someone makes a mistake and tries to create an instance without using getInstance() an error will be thrown. This is a little workaround me and Rich came up with.

package
{

	public class Singleton
	{
		private static var instance:Singleton;
		private static var creatingSingleton:Boolean = false;
		
		public function Singleton()
		{
		if( !creatingSingleton ) throw new Error( “Singleton and can only be accessed through Singleton.getInstance()” );
		}
		
		public static function getInstance():Singleton
		{
		
			if( !instance )
			{
				creatingSingleton = true;
				instance = new Singleton();
				creatingSingleton = false;
			}
		
			return instance;
		}
	}
}

posted @ 2011-03-11 20:55  lyqandgdp  阅读(185)  评论(0编辑  收藏  举报