Archive for August, 2007

AS3.0 Better Singletons


I’ve found a better more robust way of enforcing singletons in AS3.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package
{
	public class Singleton
	{
		public static var instance:Singleton;
 
		public static function getInstance():Singleton
		{
			if( instance == null ) instance = new Singleton( new SingletonEnforcer() );
			return instance;
		}
 
		public function Singleton( pvt:SingletonEnforcer )
		{
			// init class
		}
	}
}
 
internal class SingletonEnforcer{}

Note: The class “SingletonEnforcer” is actually placed within the same .as file as the Singleton class, but placed outside the package{} parenthesis, therefore, the class “SingletonEnforcer” can only be accessed from within this .as file, so if the Singleton’s constructor is called from anywhere else, you’ll get an error.

AS3.0 Reversed for loop


Today I came across an easy mistake to make when new to AS3.

I set up a for loop, to count backwards through an Array. But for some strange reason the loop was never terminating! It was simple, here’s the original code

[as]
var i:uint;
for( i=arr.length-1; i>=0; i– )
{
}
[/as]

The mistake was simple, I had set i as a uint, so it could never go below 0, so just had to make i an int. It sounds stupid once you realise it, but it wasted enough of my time!