Problems with ActionScript, Part 1
ActionScript 3.0 is the new version of the Adobe Flash scripting language. ActionScript 3.0 is supposed to be a better implementation of Object-Oriented paradigms. Through my learning of ActionScript on my latest project (A XML Object-Relational Mapper between web services), I have come across several gotchas and frankly annoying things about ActionScript.
I will be doing a several part series on the various problems I’ve encountered using ActionScript and how to get around them or how Adobe should fix them. Either way, knowledge about these things is important to the typical OO programmer looking to learn ActionScript.
Private constructors. Although not the most commonly used feature of most object-oriented languages, they are essential for one of the most famous, or infamous depending on the programmer, design patterns. The Singleton. For those not in the know, the Singleton pattern is used for enforcing only one instance of a specified class. There are many uses for this, but I’ll leave that discussion to a place with a little more room.
ActionScript 3.0 is missing private constructors. This is intriguing for two reasons. One, private constructors were allowed in ActionScript 2.0. Two, private constructors were removed with what seems to be no reason. I have been unable to find any documentation as to why they were removed. This makes implementing the Singleton pattern rather strange. So how do we do it?
package com.constellex.actionscript {
import flash.utils.getQualifiedClassName;
public class Singleton {
private static var instance:Singleton = null;
public static function getInstance() : Singleton {
if (Singleton.instance == null) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public function Singleton() {
if ( getQualifiedClassName(super)
!= "com.constellex.actionscript::Singleton" )
throw new ArgumentError();
} else {
// Your constructor code here
}
}
}
}
The only difference this ActionScript 3.0 implementation does differently is that instead of checking at compile time whether you are correctly using the Singleton object, it will throw an ArgumentError exception if you attempt to instantiate the Singleton object outside of the Singleton class. The getQualifiedClassName(super) gets the name of the class calling the method, which allows the Singleton to check and make sure only the Singleton class can call the constructor.
Next up in part 2, overloading methods.
September 3rd, 2007 at 7:30 am
respectinc.com…
Thank you for your post!…