How exactly does dependency injection reduce coupling?

前端 未结 4 467
醉梦人生
醉梦人生 2020-12-14 21:16

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 r

4条回答
  •  感情败类
    2020-12-14 21:43

    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.

提交回复
热议问题