“依赖倒置原则”是什么意思?在面向对象编程中意味着什么?

发布于 2024-09-19 19:58:02 字数 36 浏览 1 评论 0原文

面向对象编程中的“依赖倒置原则”是什么意思?它有什么作用?

What is meant by the "dependency inversion principle" in object-oriented programming? What does it do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鯉魚旗 2024-09-26 19:58:02

在面向对象编程中,
依赖倒置原则是指一种特定形式的解耦,其中从高级策略设置模块到低级依赖模块建立的传统依赖关系被倒置(例如反转),以便使高级模块独立于低级模块实现细节。

该原则规定:

A. 高层模块不应依赖于低层模块。两者都应该依赖于抽象。

B. 抽象不应依赖于细节。细节应该取决于抽象。

来源

In object-oriented programming,
the dependency inversion principle refers to a specific form of decoupling where conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are inverted (e.g. reversed) for the purpose of rendering high-level modules independent of the low-level module implementation details.

The principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.

B. Abstractions should not depend upon details. Details should depend upon abstractions.

Source

凉世弥音 2024-09-26 19:58:02

使用依赖倒置的主要原因是允许在应用程序的编译时或在运行时通过配置选择这些较低级别模块的不同实现。这对于测试来说是一个巨大的胜利,因为它允许您完全隔离正在测试的代码并使用模拟对象。

这对客户端部署有巨大帮助。假设您有不同的客户,具有不同的身份验证系统、不同的数据库、报告系统等。您可以在部署时通过更改 XML 文件来配置他们的系统,以选择要加载的这些组件的正确实现,而无需更改任何代码。

The main reason for using dependency inversion is to allow for different implementations of those lower-level modules to be selected either at compile-time in the application or at runtime by configuration. This is a big win for testing because it allows you to completely isolate the code being tested and use mock objects.

Another way this is a huge help is for client deployments. Let's say you have different customers with different auth systems, or different databases, or reporting systems, or whatever. You can configure their system at deployment time by changing an XML file to choose the right implementations of those components to load, with no code changes at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文