这个问题在这里已经有了答案:
Singleton design pattern vs Singleton beans in Spring container
(11 个回答)
5年前关闭。
What is so bad about singletons?
已经解释得很清楚了,单例设计模式违反了多个最佳实践。那为什么spring beans默认是单例的呢?这种设计不会间接导致同样的违规行为吗?
最佳答案
单例模式和 Spring 单例模式几乎没有共同之处。实际上唯一的可能是:
生产运行时只有一个实例
让我们从您链接到的答案中了解该模式的批评者:
They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.
They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.
They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.
https://stackoverflow.com/questions/41503326/