Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton Classes

 
Rohan Kayan
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to Design a class from which only one object can be created? If more than one object is created, then the program should terminate?
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Terminating the program seems like a drastic measure to me. Typically the Singleton pattern only allows one instance to be created. There is plenty of information about design patterns, so I suggest you google for it. Also, you may want to visit the OO, Patterns, UML and Refactoring forum where they discuss these kinds of things on a regular basis.

To get you started, a typical Singleton class will look something like this:


HTH

Layne
[ November 03, 2004: Message edited by: Layne Lund ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like that Layne said "typically" because, as with any other rule, there are exceptions. In fact, that sounds like me always leaving some wiggle room. Some singletons have only one instance because everybody knows that's how it should be and they never make any more. Well, they could but the object wouldn't work and they'd stop doing it pretty soon.

If you have any chance of multiple threads in your program, slap the "synchronized" keyword on your getInstance() method. Otherwise there is a risk that multiple threads will create new instances before the variable becomes non-null.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic