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
}
}
Comments