UPDATE I’ve improved on this implementation; please see the later post The Arrogant Enum.
This is about implementing an enum in AS3 with value restriction ( i.e. the programmer should be unable to diminish or add to the set of values) and type safety.
We’ll implement the data type as a Class. In order to keep the programmer from adding to the set of values, we need to disallow invocation of the constructor.
Back when AS3 came out, there was much talk about the lack of private constructors and what to do about it, especially with regard to implementing the Singleton pattern. My favorite of the solutions is to define a file-level class and require it (the class, not an instance!) as a constructor parameter.
From there we can proceed just as Daniel Savarese describes in Implementing Enumerated Types in Java.
I don’t show how to implement an ordering on the enum values. See the Savarese article for that, too.
package
{
import flash.errors.IllegalOperationError;
public final class PailContents
{
public static const WATER:PailContents = new PailContents(PrivateConstructorEnforcer, "water");
public static const CHICKENFEED:PailContents = new PailContents(PrivateConstructorEnforcer, "chicken feed");
public static const MILK:PailContents = new PailContents(PrivateConstructorEnforcer, "milk");
public static const OATS:PailContents = new PailContents(PrivateConstructorEnforcer, "oats");
private var _name:String;
public function PailContents(lock:Class, name:String)
{
super();
if (lock != PrivateConstructorEnforcer)
{
throw new IllegalOperationError("Invalid constructor access");
}
_name = name;
}
// don't forget to implement toString() to support implicit conversion to String for trace() etc:
public function toString():String
{
return _name;
}
}
}
// defined outside the package, and therefore visible only within this source file:
class PrivateConstructorEnforcer {}

Pingback: Strategies For Global Data ( hey it happens… )- Touch My Blog