aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes singleton class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "singleton class" Watch "singleton class" New topic
Author

singleton class

Mohan Ramanna
Ranch Hand

Joined: Jun 26, 2000
Posts: 36
hello friends,
I know that a singleton class is one which can have only one
instance.
I wanted to know how to make a class singleton.
thanks in advance
bye bye
-regards
mohan
lakshmi nair
Ranch Hand

Joined: Oct 11, 2000
Posts: 63
hi,
One way to acheive this is to make the constructor private and provide a public creator function(theInstance in code). The class will also have a static var of its own type.
When we call theInstance(), it returns this static instance of the class. if the variable is null(i.e., just the first time) then a new object is created. From the next time onwards the same instance is returned.
See code below...
Hope this helps
Regards,
Lakshmi
Mohan Ramanna
Ranch Hand

Joined: Jun 26, 2000
Posts: 36
thanks a lot Lakshmi,
I got the concept it is very clear now.I tird the code also.
But i would like to ask u where do we find this singleton class to be useful.
Thanks a lot.
bye
regards
-mohan
Adrian Yan
Ranch Hand

Joined: Oct 02, 2000
Posts: 688
Singleton classes are very useful especially in web development. You can use singleton classes to share things such as connection pool.
Also, sometime, you just want to have a signle instance of a class, that means you can use singleton.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
A singleton class is used when it only makes sense to have one instance of a class. The Runtime class in java is an example of a singleton class. Or perhaps you have a space simulator and you have a class Universe to represent the Universe, it only makes sense to have one instance (unless you get into multiple-dimensions etc. but that's missing the point ;-) )
------------------
*************************
When I was your age, I was twenty.
Dev Prakash
Greenhorn

Joined: Oct 09, 2000
Posts: 28
Hi lakshmi,
I guess in your code the method "theInstance" should be static, so that other class can you this class to create the new instance or use the available instance.
- dev Prakash
lakshmi nair
Ranch Hand

Joined: Oct 11, 2000
Posts: 63
Oops!!! sorry for the carelessness on my side!!!
The method must be static...
lakshmi nair
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: singleton class
 
Similar Threads
Regarding Singleton
what is the benefits of singleton ?
singleton class
Singleton class
Information about Design Patterns used by Spring.