The road so far….

June 27, 2010

Enums are Not Singleton !!

Filed under: java — Tags: , — Rahul Sharma @ 9:57 pm

After going through  couple of  blogs on Enums and associated design patterns, I started testing Enums and their behaviour especially in relation to Singleton pattern.  So I implemented a simple Enum and started to test it.

public enum MyApplicationFactory {
   ModuleOne;
   void operate() {
     System.out.println("Working On it!! ");
   }
}

public class MyAppFactoryTests {
  @Test
   public void testOne() {
     System.out.println(MyApplicationFactory.ModuleOne);
     MyApplicationFactory.ModuleOne.operate();
  }
}

This test went fine, so I added one more constant “ModuleTwo ” to Enum and that also went fine. But the problem came when I implemented a constructor in the Enum.  So now my Enum looks like this : (more…)