|
Re: Singleton Considered Harmful?
|
Posted: Sep 4, 2007 12:12 PM
|
|
I think the big problem with singletons is when the class knows that it is a singleton. IMO, you should avoid
Foo.getInstance()
instead, using DIP or some other technique, that should decide if it a class is a singleton. Ultimately, there may be some "master singleton" like an ApplicationContext, so this isn't perfect, but at least it's only one class that knows it is a Singleton.
Nearly every time I have seen a decision like "Oh, never mind, we will only ever have one Foo at a time, we can use Foo.getInstance()" that decision has been wrong.
Even Spring has an issue that, at least how we have generally implemented it, it assumes there is one ApplicationContext. When sometimes you need an alternate context, for example, if you don't want to talk to the normal database URL. This would be a case for James' idea that your "master" getInstance() method should take an argument
|
|