Meaningless Drivel is fun!*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Singleton Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Singleton" Watch "Singleton" New topic
Author

Singleton

Jim Patrick
Ranch Hand

Joined: Dec 27, 2005
Posts: 42

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

Joined: Dec 06, 2010
Posts: 448

When you don't need more than one instance. e.g. front controller, validator, xml parser etc.


Java Experience
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

Hava a look at Singleton FAQ here.

http://muhammadkhojaye.blogspot.com/
Elchin Asgarli
Ranch Hand

Joined: Mar 08, 2010
Posts: 222

Function objects should also generally be singleton.


Personal page, SCJP 6 with 91%, SCWCD 5 with 84%, OCMJD
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4462
    
    8

Elchin Asgarli wrote:Function objects should also generally be singleton.

Really? Why?
Elchin Asgarli
Ranch Hand

Joined: Mar 08, 2010
Posts: 222

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

Joined: Apr 06, 2010
Posts: 4462
    
    8

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

Joined: Mar 08, 2010
Posts: 222

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singleton