Fundamentals 7 min read

Understanding Inversion of Control (IoC) and Dependency Injection (DI)

The article explains the concept of Inversion of Control, how it reverses object creation responsibilities to a container, the benefits of loose coupling and testability, and clarifies the relationship between IoC and Dependency Injection with illustrative diagrams and references.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Understanding Inversion of Control (IoC) and Dependency Injection (DI)

2.1.1 IoC是什么

IoC—Inversion of Control, i.e., “control inversion”, is not a technology but a design philosophy; in Java development it means handing over the objects you design to a container for management instead of creating them directly inside your classes.

●谁控制谁,控制什么:传统 Java SE 程序设计中,我们在对象内部通过 new 创建依赖对象,程序主动创建;IoC 则由专门的容器创建这些对象,容器控制对象的创建,主要控制外部资源获取。

●为何是反转,哪些方面反转了:传统应用程序主动获取依赖对象(正转),而 IoC 让容器帮助创建并注入依赖对象(反转),对象被动接受依赖,依赖对象的获取被反转。

图2-1 传统应用程序示意图

当有了 IoC/DI 容器后,客户端类不再主动创建这些对象,如图2-2所示。

图2-2 有 IoC/DI 容器后程序结构示意图

1.1.2 IoC能做什么

IoC 不是技术,而是一种面向对象编程的法则,指导我们设计松耦合、优良的程序。传统程序在类内部主动创建依赖对象导致高耦合、难测;IoC 容器负责创建和注入依赖,使对象之间松散耦合,便于测试、复用并提升系统灵活性。

IoC 带来的最大改变是思想层面的“主从换位”,应用程序从主动获取资源的“老大”变为被动等待容器注入资源的角色。

IoC 体现了好莱坞法则:“别找我们,我们找你”,即容器帮助对象寻找并注入依赖。

2.1.3 IoC和DI

DI—Dependency Injection,即“依赖注入”,是组件之间的依赖关系在运行时由容器决定,容器动态将依赖注入组件,目的是提升组件复用频率并构建灵活、可扩展的平台。通过简单配置即可指定资源,无需代码关注资源来源。

关键点:谁依赖谁——应用程序依赖 IoC 容器;为什么需要依赖——获取外部资源;谁注入谁——IoC 容器注入应用程序的对象;注入了什么——外部资源(对象、资源、常量等)。

IoC 与 DI 实际上是同一概念的不同视角,Martin Fowler 在 2004 年提出“依赖注入”以更明确描述被注入对象依赖容器配置的关系。

注:想深入了解 IoC 和 DI,请参考 Martin Fowler 的经典文章《Inversion of Control Containers and the Dependency Injection pattern》。

原文地址: http://www.martinfowler.com/articles/injection.html

来源:张开涛

链接: http://sishuok.com/forum/blogPost/list/2427.html

长按识别二维码,浏览器打开

秒下大讲堂在线课程APP

支持 Android 和 iOS

Qunar 最新最热门的在线视频课程尽在其中!

对 Spring 感兴趣的同学可以在 PC 端或客户端大讲堂学习马宇申、吴昊两位老师的 Spring 视频课程~

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design PatternsIoCdependency-injection
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.