• Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton pattern  RSS feed

 
Suri Babs
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What singleton pattern?
If any one can explain with code it will be good to understand.
thanks in advance
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short version is, a singleton class is one that you want exactly one instance of. Slightly longer version is one instance per JVM.
Why would you want this? A real-life example: My current application has an object that gives out sequential numbers for use as database keys. Every object that wants to write to the database calls this object and asks for the next sequential number. If there were multiple instances of this object, they'd have a hard time keeping track of the next number. With exactly one instance, it can just keep the next number in a member variable.
Once we have the singleton concept down and want to use it in code, we run into a challenge. We can't do new because we can't create more instances. How do we get a reference to the single instance?
A common solution is for the class to act as a factory for the single instance. You see things like this:

Does that make sense?
[ April 29, 2003: Message edited by: Stan James ]
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's like Tigger who always says "The most wonderful thing about Tiggers is, I'm the only one!" Joel would be proud of me for sneaking in a quasi-zoological analogy of a singleton!
[ April 29, 2003: Message edited by: Michael Morris ]
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Michael Morris:
Joel would be proud of me for sneaking in a quasi-zoological analogy of a singleton!


[ April 30, 2003: Message edited by: Joel McNary ]
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!