| 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: 19216
|
|
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
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..!!
|
 |
 |
|
|
subject: Singleton Pattern
|
|
|