Вопрос

Is Singleton an anti-pattern? If yes, then Dependency Injection in Spring also Anti-pattern (because Spring promotes Singleton bean which is default)?

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top