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 Pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Singleton Pattern" Watch "Singleton Pattern" New topic

Singleton Pattern

Deepak Chopra
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

Hi Can someone please explain me Singleton pattern in JAVA?

When i googled it, I found following information:

Singleton pattern cause only one Object of a class will be used through out,
in Order to get that single Object of class we must implement
1) getInstance() method in the class.. and that must be declare as static

2) constructor should be private for that class, in order to avoid new SingletonClass() outside the singleton class...

3) there should be one private static variable with reference type equal to singleton class..

Is there anything I missed out, pleases remind me...?

Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Nitesh Kant

Joined: Feb 25, 2007
Posts: 1638

One important thing, if the constructor does not throw an exception then initialize the instance in a static block or inline with variable declaration.
However, there are huge number of people who discourage the use of singleton. This javaranch FAQ talks about singleton and has a lot of links.

apigee, a better way to API!
Rob Spoor

Joined: Oct 27, 2005
Posts: 20275

If the object is serializable, make sure that serialization cannot create new instances. One way is to use the (private) readResolve method:

Although called when an object is already created, it will prevent returning an equal (through equals) but different (through ==) object.

How To Ask Questions How To Answer Questions
Deepak Chopra
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

thanks a lot to both of you!!

You make my doubt clear..!!
I agree. Here's the link:
subject: Singleton Pattern
It's not a secret anymore!