依赖注入究竟是如何减少耦合的? [英] How exactly does dependency injection reduce coupling?

查看:12
本文介绍了依赖注入究竟是如何减少耦合的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了大量关于依赖注入的文章,但我不知道它实际上是如何减少耦合的?

I've done plenty of reading on Dependency Injection, but I have no idea, how does it actually reduce coupling?

我对 DI 的类比是所有组件都注册到一个容器中,因此它们就像在一个宝箱中.要获得一个组件,您显然要先注册它,然后您必须查询宝箱(这就像一个间接层).这是正确的比喻吗?不过,注入"是如何发生的并不清楚(这如何与这个类比相符?).

The analogy I have of DI is that all components are registered with a container, so theyre are like in a treasure chest. To get a component, you obviously register it first, but then you would have to interrogate the treasure chest (which is like a layer of indirection). Is this the right analogy? It doesn't make obvious how the "injection" happens, though (how would that fit in with this analogy?).

谢谢

推荐答案

用你的组件在宝箱中的类比:一个没有依赖注入的系统(比如一个宝藏抛光器)必须能够从宝箱本身中挑选一件物品.它必须了解依赖的本质,才能根据当前上下文选择正确的宝藏进行打磨.从而耦合.

To go with your analogy of your components being in a treasure chest: A system (lets say a treasure polisher) without dependency injection has to have the ability to pick an item from the treasure chest itself. It has to have some knowledge the dependency's nature in order to pick the correct treasure to polish depending on the current context. Thus coupling.

在 DI 场景中,您的宝藏抛光师根本不需要知道宝箱的存在.它需要知道的是,在某个时刻(最好是在创建时),抛光器将被提供(注入)一个实现 ITreasure 的对象:

In a DI scenario, your treasure polisher does not need to know about the existence of the treasure chest at all. All it needs to know is that at some point (preferably at creation) the polisher will be provided (injected) with an object which implements ITreasure:

interface ITreasure
{
    void PolishMe();
}

因此您的实现类与您的宝箱分离.

Thus your implementation class is de-coupled from your treasure chest.

这篇关于依赖注入究竟是如何减少耦合的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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