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
Joined: Jun 26, 2000
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
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.
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.