Digital Paper Revolution

AS3: Singleton

I don't think this trick is all that special, but I've been told I should put it on the internets. ActionScript does not allow for private constructor functions, thereby preventing a pure implementation of the Singleton pattern. This is my way around it:


public class MySingleton {
private static var inst:MySingleton;
private static var safe:Boolean = false;

public function MySingleton() {
if (MySingleton.safe) {
this.init();
} else {
throw new Error("Singleton Error");
}
}

public function instance() {
if (MySingleton.inst == null) {
MySingleton.safe = true;
MySingleton.inst = new MySingleton();
MySingleton.safe = false;
}
return MySingleton.inst;
}

private function init() {
//run init
}
}


The general idea is that instead of a private constructor, we just throw an error if someone tries to access the constructor directly. This prevents the instantiation from occurring, essentially achieving the desired effect. Of course, errors are noticeable at runtime, not compile time, but it's better than nothing.

Now, I'm not convinced this is 100% thread-safe, but since AS3 doesn't let us get at threads, I think the point is moot.

Comments