• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton

 
Jim Patrick
Ranch Hand
Posts: 42
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

I know what a singleton pattern means. but when do we need to use this pattern(in what situations)?

Regards,
Jim
 
Sunny Bhandari
Ranch Hand
Posts: 448
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you don't need more than one instance. e.g. front controller, validator, xml parser etc.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hava a look at Singleton FAQ here.
 
Elchin Asgarli
Ranch Hand
Posts: 222
Chrome Eclipse IDE Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Function objects should also generally be singleton.
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Elchin Asgarli wrote:Function objects should also generally be singleton.

Really? Why?
 
Elchin Asgarli
Ranch Hand
Posts: 222
Chrome Eclipse IDE Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:
Elchin Asgarli wrote:Function objects should also generally be singleton.

Really? Why?


Because unless they have an internal state, it is unnecessary to create new function objects every time.
In Effective Java Item 21 its described for Comparator objects, however the same can be applied to every function object with no internal state. There is a bit more info in my blog post
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Elchin Asgarli wrote:Because unless they have an internal state, it is unnecessary to create new function objects every time.

There can be an internal state, though, especially when you're using anonymous inner classes (which is a common way of implementing function objects).

I'd make a distinction between cases when you definitely should not have more than one instance, and cases where there is no need for more than one. I'd usually only use a Singleton pattern for the former.
 
Elchin Asgarli
Ranch Hand
Posts: 222
Chrome Eclipse IDE Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course when there is an internal state, it must not be a singleton.

Matthew Brown wrote:
I'd make a distinction between cases when you definitely should not have more than one instance, and cases where there is no need for more than one. I'd usually only use a Singleton pattern for the former.


I use for both, since it gives me a performance benefit.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic