• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton Pattern

 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...?
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20609
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot to both of you!!

You make my doubt clear..!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic