全局VS依赖注入 [英] Globals vs dependency injection

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

问题描述

有人说,这是更好地使用依赖注入。这是为什么?

Some people say that it is better to use dependency injection. Why is that?

我觉得最好是有一些全局,出入方便类,而不是巨大的构造。

I think it is better to have few global, easy accessible classes, rather than huge constructors.

这会影响应用程序的速度以任何方式?

Does it influence application speed in any way?

这两个的搭配将是可能是最好的。

Mix of these two would be probably the best.

推荐答案

主要优势会的去耦的,这将单元测试帮助。这种完全取决于你如何编写这些方便类。

The main advantage will be decoupling, which will help with unit testing. This sort of depends entirely on how you code these "easily accessible classes".

的想法是这样的。一类从分离出来的实施的()仅具有对的合同的(接口)。在真实环境中,你可能永远也提供了新的实现类,但在测试环境中,你的很可能的会(无论是手工制作的存根,或嘲弄的框架嘲笑类)。

The idea is this. A class decouples from implementation (class) dependencies by only having a dependency on the contract (interface). In your live environment you may never provide a new implementing class, but in your test environment you very likely will (be it a handmade stub, or a mocked class from a mocking framework).

应用程序的速度将需要分析,但使用的DI框架中可能会产生一些开销,而不是你直接对话,你知道单身。重要的问题:就是这方面的开销有问题吗?只有业绩预期和分析可以告诉你。在我的经验,好处远远大于可以忽略不计的性能造成损害。

Application speed would need profiling, but the use of a framework for DI would likely incur some overhead instead of you talking directly to a singleton that you know about. The important question: is this overhead a problem? Only performance expectations and profiling can tell you that. In my experience, the benefits far outweigh the negligible performance detriment.

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

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