Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Singleton an Anti-pattern?

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

like image 741
Silent Warrior Avatar asked Jan 30 '26 07:01

Silent Warrior


1 Answers

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.

like image 97
Joachim Sauer Avatar answered Feb 01 '26 21:02

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!