Reputation: 5285
Is Singleton an anti-pattern? If yes, then Dependency Injection in Spring also Anti-pattern (because Spring promotes Singleton bean which is default)?
Upvotes: 2
Views: 2349
Reputation: 120851
The Singleton pattern is no anti-pattern, it is a patter to restrict the number of instances for an object.
But abuse the singleton to provide global instances is a anti-pattern.
For the spring part of your question see Joachim Sauer answer.
Upvotes: 4
Reputation: 308159
There's an important difference between hard-coding a singleton and using Spring to create a singleton bean: the latter is just configuration.
As such Spring doesn't prevent testability: it's a single use-case where a bean is used as a singleton. You can easily use the same spring by manually instantiating it in a test, or replacing it with a mocked implementation of the same interface.
If you code a class as a singleton then you can't easily replace it, without rewriting it. Testing is just a single example where you might want to replace it. If you realize that you'll need two different instances of that bean, then you're stuck with a hard-coded singleton as well.
Upvotes: 5