我正在学习 Spring 。我了解依赖注入(inject)。在某些地方我也看到它称为依赖倒置。我知道为什么它被称为注入(inject),但“反转”是什么意思?它实际上反转了哪种依赖性?
最佳答案
好问题 - inversion
这个词有点令人惊讶(因为在应用 DIP 之后,较低级别的依赖模块显然不再 depend
到较高级别级别的调用者模块,或者 - 调用者和依赖项现在通过额外的抽象更加松散地耦合)。
引用 Robert C Martin 的 original source
One might question why I use the word “inversion”. Frankly, it is because more traditional software development methods, such as Structured Analysis and Design, tend to create software structures in which high level modules depend upon low level modules, and in which abstractions depend upon details. Indeed one of the goals of these methods is to define the subprogram hierarchy that describes how the high level modules make calls to the low level modules. ... Thus, the dependency structure of a well designed object oriented program is “inverted” with respect to the dependency structure that normally results from traditional procedural methods.
阅读 Uncle Bob 关于 DIP 的论文时需要注意的一点是 C++(和 at time of writing, still doesn't)没有接口(interface),因此在 C++ 中实现这种抽象通常是通过抽象/纯虚拟基类实现的,而在Java 或 C# 松散耦合的抽象通常是通过从依赖项中抽象接口(interface)并将更高级别的模块耦合到接口(interface)来解耦。
编辑 澄清一下:
"In some place I also see it called dependency inversion"
请注意 Dependency Injection (DI)是实现依赖倒置原则 (DIP) 的可能实现之一 - the "D" in SOLID design principles ,所以 DI
和 DIP
不能完全互换。
其他 DIP 实现包括 Service locator pattern (现在是 often regarded 作为反模式);和 Plugin .
关于java - 依赖倒置中的 'Inversion'是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978841/