It's not a secret anymore!*
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
Author

Singleton Pattern

Sunny Jain
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
Bartender

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
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

thanks a lot to both of you!!

You make my doubt clear..!!
 
GeeCON Prague 2014
 
subject: Singleton Pattern