• Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton in Java  RSS feed

 
Alexei Vinogradov
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
what make the implementation of singleton with getInstance() static method and private constructor more attractive as a plain class with only static methods? Only that former is "object-oriented" ?
Or are there some other differences that i do not see?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Alexei Vinogradov:
what make the implementation of singleton with getInstance() static method and private constructor more attractive as a plain class with only static methods? Only that former is "object-oriented" ?

It doesn't make it inherently more attractive. Object orientation is a tool for decoupling, not a goal in itself.
In this specific case, the Singleton pattern encapsulates the actual number of instances used and their classes.
See http://test.javaranch.com/wiki/view?SingletonPattern for more info.
[ September 28, 2003: Message edited by: Ilja Preuss ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Singleton is best used for something that there must be exactly one of. For example, if I'm going to implement a connection pool I'll want exactly one pool manager.
The dark side of a Singleton is that it also smells a lot like a global variable. Java left out global variables on purpose because they can easily become an evil violation of encapsulation and all kinds of good OO practices. I sometimes use Singleton to ease navigation to an object, but it's a choice of last resort and in my own head it's a point against me for doing it.
BTW: Static member variables have roughly the same pros & cons.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!