Win a copy of Getting started with Java programming language this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton: is instance needed?  RSS feed

 
Piet Souris
Rancher
Posts: 1769
51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Jeannes and Scotts OCPJP study guide, in chapter 2, there is an example of of a Singleton called HayStrorage, on page 77. My question: why is an instance needed? If you use this singleton:

what would be the disadvantage?
 
Ankit Garg
Sheriff
Posts: 9599
36
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm assuming you've modified the code to make the methods and fields static. Singleton is more powerful than using a class with everything static in some cases:

Polymorphism: Since the singleton is an instance, you can use the instance as a regular object. So you can pass it to other methods which is especially useful if your singleton class implements an interface.

Lazy Loading: If the singleton object is heavy, you can lazy load it inside the getInstance method...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!