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

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

问题描述

我已经做了很多关于依赖注入的阅读,但是我不知道如何减少耦合度。



我有DI的类比是所有组件都在容器中注册,所以它们就像在宝箱里。要获得一个组件,你首先要注册,但是你必须询问宝箱(这就像一层间接的)。这是正确的比喻吗?不过,注入发生的方式并不明显(但是,与此类比如何)?



谢谢

解决方案

与您的组件在宝箱中的比较:
无依赖注入的系统(让我们说宝贝抛光机)必须有从宝箱本身挑选物品的能力。它必须有一些依赖性的知识,以便根据当前的情况选择正确的宝藏来抛光。因此耦合。



在DI方案中,您的宝石抛光机完全不需要知道宝箱的存在。所有它需要知道的是,在某些时候(最好在创建时)抛光机将被提供(注入)一个实现 ITreasure 的对象:

 界面ITreasure 
{
void PolishMe();
}

因此,您的实现类从您的宝箱中脱离。 >

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

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

Thanks

解决方案

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.

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天全站免登陆