Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton Using Enum Query

 
vipul bondugula
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers,

Currently we are migrating our project from java 1.4 to 1.5. In 1.4 we used singleton using static factory method. But for 5 version we want to use singleton using enum.

suppose for example:



my doubt is
singleton means only one object will created. but singleton using enum , as in the above program multiple objects are created.

that breaks singleton rule. please clarify me.

Thanks & Regards,
Vipul Kumar.
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're using an enum, the JVM guarantees only one instance of each value gets created. So in this example, only one instance of MyEnum is ever created however you try and refer to it.

Try printing out m1 == m2 etc if you don't believe that.

By the way, as things stand your MyEnum won't actually compile. You don't need a getInstance() method (just refer to MyEnum.INSTANCE as you have later). But if you want it for some reason it should be static, it shouldn't return int, and it should just return INSTANCE rather than this.INSTANCE. (Oh yes, and INSTANCE should be spelled correctly ).

Out of interest, are you really migrating to Java 1.5? Java 6 came out nearly 6 years ago, and Java 7 a year ago. If you're going to the trouble of upgrading, you might as well go to a current platform.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic