Meaningless Drivel is fun!
The moose likes OO, Patterns, UML and Refactoring and the fly likes Singleton Using Enum Query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Singleton Using Enum Query" Watch "Singleton Using Enum Query" New topic

Singleton Using Enum Query

vipul bondugula
Ranch Hand

Joined: Oct 14, 2010
Posts: 219
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.

Vipul Kumar
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

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.
I agree. Here's the link:
subject: Singleton Using Enum Query
jQuery in Action, 3rd edition