IOC and dependency inversion control injection DI detail Edition

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43170213/article/details/100079725

IoC - Inversion of Control invert
DI - Dependency Injection dependency injection

    要想理解上面两个概念,就必须搞清楚如下的问题:

Who are the participants?
Dependence: Who depends on whom? Why rely on?
Injection: Who is injected to whom? What in the end the injection?
Inversion of Control: Who controls? What control? Why it is called inversion (reversal should have a positive turn)?
Dependency Injection and Inversion of Control is the same concept right?
Here's a brief answer the above questions, these questions figured it out, IoC / DI will understand.
(1) Participants who have:

    一般有三方参与者,一个是某个对象;一个是IoC/DI的容器;另一个是某个对象的外部资源。
    又要名词解释一下,某个对象指的就是任意的、普通的Java对象; IoC/DI的容器简单点说就是指用来实现IoC/DI功能的一个框架程序;对象的外部资源指的就是对象需要的,但是是从对象外部获取的,都统称资源,比如:对象需要的其它对象、或者是对象需要的文件资源等等。

(2) who depend on who:

    当然是某个对象依赖于IoC/DI的容器

(3) Why rely on:

    对象需要IoC/DI的容器来提供对象需要的外部资源

(4) Who is injected to whom:

    很明显是IoC/DI的容器 注入 某个对象

(5) what in the end is injected:

    就是注入某个对象所需要的外部资源

(6) Who controls who:

    当然是IoC/DI的容器来控制对象了

(7) What control:

    主要是控制对象实例的创建

(8) Why is called reverse:

    反转是相对于正向而言的,那么什么算是正向的呢?考虑一下常规情况下的应用程序,如果要在A里面使用C,你会怎么做呢?当然是直接去创建C的对象,也就是说,是在A类中主动去获取所需要的外部资源C,这种情况被称为正向的。那么什么是反向呢?就是A类不再主动去获取C,而是被动等待,等待IoC/DI的容器获取一个C的实例,然后反向的注入到A类中。


    用图例来说明一下,先看没有IoC/DI的时候,常规的A类使用C类的示意图,如图7所示:

Here Insert Picture Description
A schematic diagram of a conventional used in FIG. 7 C

When there IoC / DI container, A Class C to create a longer active, 8:
Here Insert Picture Description
FIG. 8 is no longer actively created Class A C

Instead passively wait, wait IoC / DI obtain an instance of a container C, and then injected into a reverse class A, as shown in Figure 9:
Here Insert Picture Description
Figure 9 a schematic diagram of the program structure IoC / DI container

        (9)依赖注入和控制反转是同一概念吗?


    根据上面的讲述,应该能看出来,依赖注入和控制反转是对同一件事情的不同描述,从某个方面讲,就是它们描述的角度不同。依赖注入是从应用程序的角度在描述,可以把依赖注入描述完整点:应用程序依赖容器创建并注入它所需要的外部资源;而控制反转是从容器的角度在描述,描述完整点:容器控制应用程序,由容器反向的向应用程序注入应用程序所需要的外部资源。

(10) Summary about:

    其实IoC/DI对编程带来的最大改变不是从代码上,而是从思想上,发生了“主从换位”的变化。应用程序原本是老大,要获取什么资源都是主动出击,但是在IoC/DI思想中,应用程序就变成被动的了,被动的等待IoC/DI容器来创建并注入它所需要的资源了。
    这么小小的一个改变其实是编程思想的一个大进步,这样就有效的分离了对象和它所需要的外部资源,使得它们松散耦合,有利于功能复用,更重要的是使得程序的整个体系结构变得非常灵活。

Guess you like

Origin blog.csdn.net/qq_43170213/article/details/100079725