控制反转与依赖注入

控制反转和依赖注入

最近入职了新公司,新公司用的是 Guice 框架进行的依赖注入, 为了学习 Guice,先复习一遍IOC 和 DI

Inversion of Control 控制反转

以下是来源于一个国外网站的解释

Inversion of Control is a principle in software engineering which transfers the control of objects or portions of a program to a container or framework. We most often use it in the context of object-oriented programming.

个人翻译一下就是:

软件工程中的控制反转,就是指将对象或者程序的某一部分的控制权交给容器或者框架. 我们经常在 OOP 开发时使用到这种思想

IoC enables a framework to take control of the flow of a program and make calls to our custom code

这句话就是核心了,IoC 让框架来控制程序流并且调用我们自己的代码

The advantages of this architecture are(IoC 的优点):

  • decoupling the execution of a task from its implementation 将程序的实现与执行分离
  • making it easier to switch between different implementations 使在不同实现的切换更加简单
  • greater modularity of a program 程序模块化程度更高
  • greater ease in testing a program by isolating a component or mocking its dependencies, and allowing components to communicate through contracts 通过隔离组件或模拟其依赖项,并允许组件通过合约进行通信,从而更轻松地测试程序

Dependency Injection 依赖注入

Dependency injection is a pattern we can use to implement IoC, where the control being inverted is setting an object’s dependencies.

依赖注入是一种我们可以用来实现 IoC 的模式,其中被反转的控制是设置对象的依赖关系。

也就是说设置对象的依赖关系这个事儿从程序员来干变成让程序来干了

区别

来看一下传统方式注入依赖的方法

1
2
3
4
5
6
public class Store {
private Item item;
public Store(){
item = new ItemImpl1();
}
}

也就是说我们需要在构造 Store 的时候自己new一个 Item 的一个实现类的实例,然后注入

如果使用依赖注入 DI,我们忽略具体的Item 接口实现类

1
2
3
4
5
6
public class Store {
private Item item;
public Store(Item item){
this.item = item;
}
}

这就是依赖注入模式下的构造函数

当然具体实现类是怎么注入的, 交给框架来实现

主要是要充分理解 IoC 和 DI 的思想,这是最重要的

参考资料

  1. https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring