File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Singleton Classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Singleton Classes" Watch "Singleton Classes" New topic

Singleton Classes

Rohan Kayan
Ranch Hand

Joined: Sep 17, 2004
Posts: 123
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?

SCWCD 1.4, SCJP 1.4
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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:


[ November 03, 2004: Message edited by: Layne Lund ]

Java API Documentation
The Java Tutorial
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Singleton Classes
It's not a secret anymore!