全局与依赖注入(Globals vs dependency injection)

系统教程 行业动态 更新时间:2024-06-14 16:55:58
全局与依赖注入(Globals vs dependency injection)

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

我认为最好是有几个全球性的,容易接近的课程,而不是庞大的构造函数。

它以任何方式影响应用程序速度?

这两个组合可能是最好的。

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.

最满意答案

主要优点是解耦 ,这将有助于单元测试。 这完全取决于你如何编写这些“易于访问的类”。

这个想法是这样的。 一个类通过只依赖合约 ( interface )而从实现 ( class )依赖关系中解耦。 在你的实际环境中,你可能永远不会提供一个新的实现类,但是在你的测试环境中,你很可能会(不论是手工制作的存根,还是来自模拟框架的模拟类)。

应用程序速度需要分析,但是使用DI框架可能会产生一些开销,而不是直接与您了解的单例进行对话。 重要的问题是:这种开销是一个问题吗? 只有性能预期和性能分析才能告诉你。 根据我的经验,这些好处远远超过可忽略的性能损害。

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).

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.

更多推荐

本文发布于:2023-04-10 11:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/84237795e72d694b5fb3fb305cf26346.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局   Globals   injection   dependency

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!