Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singelton pattern versus all fields static  RSS feed

 
Rajagopal Manohar
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a class for which one one instance should be maintained. How should I go about it, use a singelton design pattern a static Instance which is returned every time or have all the field made static.

What will the relative merits and demerits be

Thanking in advance,
Rajagopal
 
Rick Beaver
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think it matters to be honest. I think it is a just a preference thing. Some people I work with like to use the getInstance() method of creating a singleton, other just use a class with only static methods.

Whichever you prefer
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your requirement is to have a class for which you need to guarentee there is only one instance per JVM, then a Singleton is your only option. If you just need a class which provides configuration-type data, then either fit.
 
Rajagopal Manohar
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thaks for the replies guys,

It is for configuration type of data so either fit would be fine I guess. I was doing code review and came across a class with all fields static because they wanted the instance to be shared but none of the methods were static.

I found this queer and wanted to suggest singleton pattern but now I will limit myself by asking them to make the methods(only get,set methods) static.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Singletons and static utility methods both have hazards. This may get me tossed from the "beginner" forum, but be aware that both can make it hard to extend, override or replace classes later down the road. For example I use a static Logger.log(message) method in all my code at home. The static method is very convenient, but I'd be in real trouble if I had to mix and match different loggers in my existing projects. If that sounds interesting, scroll on down to the UML, OO, etc. forum and ask about it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!