wood burning stoves 2.0*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Singleton Using Enum Query" Watch "Singleton Using Enum Query" New topic
Author

Singleton Using Enum Query

vipul bondugula
Ranch Hand

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

Thanks
Vipul Kumar
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

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: http://aspose.com/file-tools
 
subject: Singleton Using Enum Query
 
Similar Threads
i want some information related to enum keyword
JPA enum mapping by explicit getId()
Enums (Is this the best way)?
enums do not allow access to static members within constructors and instance init blocks
protected allowed in enum. So extending enum types possible?