Saturday, January 1, 2011

Design Patterns: Enumeration

Enumeration is often used when the list of variable is always fixed. For example the days in a single week can be written as:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

However there is often a problem of testing the Enumeration. I have to get back to my codes to know the violations of using default enum. I believe enum cannot exist as a class and hence you will have to replicate enum across the class that is using it. I chance upon the following clever get-around solution using Java object class.

This is the sample code for Java Enumeration:

class Day{

  private final String name;
  private static int nextOrdinal = 0;
  private final int ordinal = nextOrdinal++;

  protected Day(String name){
    this.name = name; 
  }

  public String getName(){
    return this.name;
  }
  public int getOrdinal(){
    return this.ordinal;
  }

  //creating your enum
  public static final Day Mon = new Day("monday");
  public static final Day Tue = new Day("tuesday");
  public static final Day Wed = new Day("wednesday");
  public static final Day Thur = new Day("thursday");
  public static final Day Fri = new Day("friday");
  public static final Day Sat = new Day("saturday");
  public static final Day Sun = new Day("sunday");
  //override equals method

  public boolean equals(Object o){
    Day objE =  (Day) o;
    return ( this.ordinal == objE.getOrdinal() );
  } 
}

There are things to take note:
  1. The use of protected construction to prevent the instantiation of Day class
  2. Use of final ordinal and static nextOrdinal to issue a unique number for a new Enum. Mon will get ordinal 1, Tue get ordinal 2 and so on....
  3. Use of overridden equals method as a more efficient way to compare object instead of using String

Hope this helps. Have a nice day ahead!

ps: I have a improved version of Enumeration

No comments:

Post a Comment