什么是依赖倒置原则,为什么它很重要? [英] What is the dependency inversion principle and why is it important?

查看:33
本文介绍了什么是依赖倒置原则,为什么它很重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是依赖倒置原则,为什么它很重要?

What is the dependency inversion principle and why is it important?

推荐答案

查看此文档:依赖倒置原则.

它基本上说:

  • 高级模块不应依赖于低级模块.两者都应该依赖于抽象.
  • 抽象不应该依赖于细节.细节应取决于抽象.

至于为什么它很重要,简而言之:更改是有风险的,通过依赖于概念而不是实现,您可以减少呼叫站点更改的需要.

As to why it is important, in short: changes are risky, and by depending on a concept instead of on an implementation, you reduce the need for change at call sites.

有效地,DIP 减少了不同代码段之间的耦合.这个想法是,虽然有很多实现方式,比如日志工具,但你使用它的方式应该是相对稳定的.如果您可以提取一个表示日志记录概念的接口,那么该接口在时间上应该比它的实现稳定得多,并且调用站点应该受您在维护或扩展该日志记录机制时所做的更改的影响要小得多.

Effectively, the DIP reduces coupling between different pieces of code. The idea is that although there are many ways of implementing, say, a logging facility, the way you would use it should be relatively stable in time. If you can extract an interface that represents the concept of logging, this interface should be much more stable in time than its implementation, and call sites should be much less affected by changes you could make while maintaining or extending that logging mechanism.

通过使实现依赖于接口,您可以在运行时选择哪种实现更适合您的特定环境.根据不同的情况,这也可能很有趣.

By also making the implementation depend on an interface, you get the possibility to choose at run-time which implementation is better suited for your particular environment. Depending on the cases, this may be interesting too.

这篇关于什么是依赖倒置原则,为什么它很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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