Tuesday, July 10, 2007

ActionScript3 singletons

Turns out it is kinda hard to do a singleton in ActionScript3. This is due to the fact that AS3 only allows public constructors, which makes it hard to prevent instantiations.

This dude, and this dude, mention a solution where you use a trick with declaring a class outside package, which is then only accessible from singleton class. Another solution is mentioned here, which looks kinda clean.

Of course, I have my own solution too:
package com.foo.bar {
public class Singleton {
private static var singleton : Singleton = null;
private static var calledFromGetInstance : Boolean = false;

public function Singleton() {
// This little trick is due to AS3 only allowing public constructors
if (!calledFromGetInstance) {
throw new Error("this is a singleton - use getInstance() to obtain the singleton instance")
}
calledFromGetInstance = false; // reset value back
}

public static function getInstance() : Singleton {
if (singleton == null) {
calledFromGetInstance = true;
singleton = new Singleton();
}
return singleton;
}
}
}

My trick is the use of calledFromGetInstance, which is private and static to the singleton type, hence only allowed to be set from within the singleton type. You can still try to create an instance from the outside, but you will be slapped!

1 comment:

Sergey Kovalyov said...

Hello! It seems that you are from Denmark. I work for Danish company now. We develop applications using Adobe Flex and PHP on back end. :)