• Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton: Static vs instance  RSS feed

 
Kumar Nat
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A singleton can be implemented as
1. Static class with constructor declared provate.
2. constructor declared provate but with a getInstance() ensuring only one instance exists at any given time.
My questions are:
a) What is the difference in the approaches. How does java handle them differently?
b) What are the pros and cons of each approach. When is one used as opposed to the other?
Thanx Much
Regards
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have a class that consists of a bunch of services (convenience) methods, then you could consider creating a class with all "static" methods and a "private" constructor. This is how the "java.lang.Math" class is defined and it works fine and dandy.
Keep in mind that static methods don't have any concept of "this" or "super" and so you can't really subclass this type of class and so you lose any potential polymorphic behaviour.
When I first started using Java I tended towards option #1 (class with static methods), but not I tend to favor option #2 just because it allows me a little more potential flexibility down the road.
I think that the performance differences between the two options are negligible. I image you could "google" on this and come up with a lot of hits where you could further explore the differences.
 
Aneesha Singh
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
I think the following article may be helpful:
http://www.javaworld.com/javaworld/jw-01-2001/jw-0112-singleton.html
Lazy initialization is another advantage of option 2.
Hope the article helps. (I just pasted it on another thread as well )
Cheers!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!