问题描述
我们如何识别何时使用依赖注入或单例模式。
我已经阅读了许多网站,他们说使用依赖注入单一模式。但我不知道我是否完全同意他们的看法。对于我的中小规模项目,我绝对看到使用单例模式直接。
例如Logger。我可以使用 Logger.GetInstance()。Log(...)
但是,为什么我需要注入我创建的每个类,记录器的实例?
如果要验证什么被登录在测试中,则需要依赖注入。此外,一个记录器很少是一个单例 - 通常你每个类都有一个记录器。
,您将看到为什么单身人士是坏的。
单身人士的问题是,它们代表一个难以预测的全球性状态,特别是在测试中。
请记住,一个对象可以是事实上的单身,仍然是通过依赖注入获得的,而不是通过 Singleton.getInstance()
。
我刚刚上市Misko Hevery在演讲中提出的一些重点。看完之后,您将获得充分的观点,了解为什么更好地让对象定义其依赖关系的,但不能定义如何创建他们的方式。 >
How do we identify when to use dependency injection or singleton pattern.I have read in lot of websites where they say "Use Dependency injection over singleton pattern". But I am not sure if I totally agree with them. For my small or medium scale projects I definitely see the use of singleton pattern straightforward.
For example Logger. I could use Logger.GetInstance().Log(...)
But, instead of this, why do I need to inject every class I create, with the logger's instance?.
If you want to verify what gets logged in a test, you need dependency injection. Furthermore, a logger is rarely a singleton - generally you have a logger per each of your class.
Watch this presentation on Object-oriented design for testability and you'll see why singletons are bad.
The problem with singletons is that they represent a global state which is hard to predict, especially in tests.
Have in mind that an object can be de-facto singleton but still be obtained via dependency-injection, rather than via Singleton.getInstance()
.
I'm just listing some important points made by Misko Hevery in his presentation. After watching it you will gain full perspective on why it is better to have an object define what its dependencies are, but not define a way how to create them.
这篇关于依赖注射单身设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!