Fake Enum in Actionscript 3

Enum having lot of sense in Object oriented programming.Please try with this example
public class TypesafeEnum
{

	private var name : String;

	public static const FILE :TypesafeEnum = new TypesafeEnum("file");
	public static const EDIT :TypesafeEnum = new TypesafeEnum("edit");
	public static const FORMAT :TypesafeEnum = new TypesafeEnum("format");
	public static const VIEW :TypesafeEnum = new TypesafeEnum("view");

	public function TypesafeEnum(name : String)
	{
	    this.name = name;

	}

	public function toString(): String {
	    return name;
	}
}

(or)

package
{
	class Direction
	{
		/*
		 * The actual enumeration values. Note that the sorting order doesn't matter.
		 */
		public static const NONE:Direction	= new Direction(NONE);
		public static const UP:Direction	= new Direction(UP);
		public static const DOWN:Direction	= new Direction(DOWN);
		public static const LEFT:Direction	= new Direction(LEFT);
		public static const RIGHT:Direction	= new Direction(RIGHT);

		/* Constructor */
		public function Direction(d:Direction)
		{
			/*
			 * Empty fake constructor
			 * The part that matter is that it accepts a 'copy' of itself
			 * For the recursive assignment to work
			 */
		}
		public function toString()
		{
			switch(this) {
				case Direction.UP:
					return "Up";
				case Direction.DOWN:
					return "Down";
				case Direction.LEFT:
					return "Left";
				case Direction.RIGHT:
					return "Right";
				default:
					/* Direction.NONE is considered 'undefined' (no direction) */
					return "undefined";
			}
		}
	}
}

-------------
 Test Case
-------------

private function testCase(): void {

    testEnum(TypesafeEnum.FILE);

}

private function testEnum(thisValue: TypesafeEnum): void {

    switch (thisValue) {
        case TypesafeEnum.EDIT:
            trace(TypesafeEnum.EDIT.toString());
            break;
        case TypesafeEnum.FILE:
            trace(TypesafeEnum.FILE.toString());
            break;
        case TypesafeEnum.FORMAT:
            trace(TypesafeEnum.FORMAT.toString());
            break;
        case TypesafeEnum.VIEW:
            trace(TypesafeEnum.VIEW.toString());
            break;

    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s