In order to be a true enum it needs to both:
- Enforce type safety
- Prevent rogue instances
Few of the simple solutions do both, and the base classes that do are overly complex IMO.
My current favourite is the following style - safe and simple, and shouldn't confuse anyone:
public final class FruitEnum {
private static const CREATE:Object = {};
public static const APPLE:FruitEnum = new FruitEnum(CREATE);
public static const ORANGE:FruitEnum = new FruitEnum(CREATE);
public static const BANANA:FruitEnum = new FruitEnum(CREATE);
public function FruitEnum(permission:Object) {
if (permission !== CREATE){
throw new Error("Enum cannot be instantiated from outside");
}
}
}
CAVEAT: I have seen rare circumstances where a variable initialisation reads an enum const before it set, but in those cases the problem applied equally to other const-based enum emulations.