enum factory method


July 25th, 2007

People that have had to deal with Design Patterns would be familiar with the Factory Method. One of the projects I’m working on requires creating classes depending on what types are specified in an XML configuration file, something like:

<hacker name=""/>

So we need to instantiate the object based on the name or type attribute. Enter the Factory Method and my little way of doing it, via an EnumFactory:


public enum HackerFactory {
LAMO { public Hacker getHacker() { return new Lamo(); } },
MITNICK { public Hacker getHacker() { return new Mitnick(); } },
GOLDSTEIN { public Hacker getHacker() { return new Goldstein(); } },
ABENE { public Hacker getHacker() { return new Abene(); } };


public abstract Hacker getHacker();
}

This is the Enum class. To actually instantiate, considering that our parsed XML lives in a String name object, the code is simply:

Hacker h = HackerFactory.valueOf(name).gethacker();

Some might argue that an Enum is not very extensible - while that’s true, the limitation exists also in the Factory Method so we’re not actually polluting our code further. Changes still need to happen only in one place - the Enum class - to reference the new additions. Where an implementation does not exist, the Enum will throw the appropriate Exception to the user.

  • Slashdot
  • Reddit
  • Digg
  • StumbleUpon
  • Facebook
  • del.icio.us
  • Technorati
  • Google
  • YahooMyWeb
  • Live
  • Mixx
  • TwitThis

Post a Comment