Some design patterns require the use of a static initializer, a block of code that should execute once and only once the first time a class is referred to. The typical use for this pattern in ActionScript programming is when a mix-in class needs to be used, as in the case of the mx.events.EventDispatcher class. EventDispatcher contains a static method, EventDispatcher.initialize(), which can be invoked to add the event framework methods to any arbitrary class.
Say we have a class called ActionManager that needs the event handling mix-in methods. One approach would be to invoke EventDispatcher.initialize(this) in ActionManager’s constructor method; however, this approach suffers from the drawback that the EventDispatcher initializer could be invoked multiple times (each time a new ActionManger instance is created), when it really only should be invoked once.
If we were programming in Java, we’d be able to do something like this, using the static initializer syntax:
public class ActionManager {
static {
mx.events.EventDispatcher.initialize(ActionManager.class);
}
public ActionManager() {
...
}
...
}
Now, ActionScript doesn’t have this sort of static block syntax, but fortunately there is a way to accomplish the same thing:
class ActionManager {
private var staticInitialized:Boolean = staticInitializer();
private static function staticInitializer(Void):Boolean {
mx.events.EventDispatcher.initialize(ActionManager.prototype);
return true;
}
public function ActionManager(Void) {
...
}
}
The ActionScript pattern illustrated above does the same thing as Java’s static initializer block syntax — the staticInitializer() method will only be called once, the first time the class is referenced, and before the constructor method is invoked.
Although this pattern is typically used to set up mix-in classes such as EventDispatcher, it is also useful for setting up arbitrary static class memebers such as lookup tables, etc., which only need to be calculated once across all instances of a class.
March 14, 2007 at 3:03 pm
Doesn’t the variable ‘staticInitialized’ need to be defined static itself? Won’t staticInitializer() get called at every ActionManager instantiation?
September 2, 2008 at 11:58 pm
for them, who googling:
in AS3.0 it works like that:
http://www.barneyb.com/barneyblog/2007/11/02/enums-and-actionscripts-static-initializers/