| 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: 446
|
|
|
When you don't need more than one instance. e.g. front controller, validator, xml parser etc.
|
 |
Muhammad Khojaye
Ranch Hand
Joined: Apr 12, 2009
Posts: 341
|
|
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: 3863
|
|
Really? Why?
|
 |
Elchin Asgarli
Ranch Hand
Joined: Mar 08, 2010
Posts: 222
|
|
Matthew Brown wrote:
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: 3863
|
|
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.
|
 |
 |
|
|
subject: Singleton
|
|
|