依赖注入单例设计模式 [英] Dependency Injection & Singleton Design pattern

查看:43
本文介绍了依赖注入单例设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何确定何时使用依赖注入或单例模式.我在很多网站上都读过他们说使用依赖注入而不是单例模式".但我不确定我是否完全同意他们的看法.对于我的中小型项目,我肯定会直接使用单例模式.

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.

例如记录器.我可以使用 Logger.GetInstance().Log(...)但是,不是这个,为什么我需要用记录器的实例注入我创建的每个类?

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.

请记住,对象可以是事实上的单例对象,但仍然可以通过依赖注入获得,而不是通过 Singleton.getInstance().

Have in mind that an object can be de-facto singleton but still be obtained via dependency-injection, rather than via Singleton.getInstance().

我只是列出了 Misko Hevery 在他的演讲中提出的一些重要观点.看完之后,您将全面了解为什么让对象定义它的依赖项更好,而不是定义如何创建依赖项的方式.

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.

这篇关于依赖注入单例设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆