定义:
-
In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies.
Inversion of Control(IOC):控制反转。 是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。
其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,**对象在被创建的时候,由一个调控系统内所有对象的外界实体,将其所依赖的对象的引用传递给它。**也可以说,依赖被注入到对象中。 -
Dependency: ClassA 中 含有 ClassB 的实例,就称ClassA对ClassB有一个依赖。
-
Dependency Injection: 直接在构造函数初始化是一种Hard init方式。可以在外部实例化ClassB后,传入ClassA中构造依赖关系。这种非自己主动初始化依赖,而通过外部来传入依赖的方式,就称为依赖注入
-
硬初始化(hard init):这种在MovieLister中创建MovieFinderImpl的方式,使得MovieLister不仅仅依赖于MovieFinder这个接口,它还依赖于MovieListImpl这个实现。 这种在一个类中直接创建另一个类的对象的代码,和硬编码(hard-coded strings)以及硬编码的数字(magic numbers)一样,是一种导致耦合的坏味道,我们可以把这种坏味道称为硬初始化。
依赖注入的实现方式:
- 构造函数注入(Construction Injection)
public class MovieLister {
private MovieFinder finder;
public MovieLister(MovieFinder finder) {
this.finder = finder;
}
}
- setter注入
public class MovieLister {
public void setFinder(MovieFinder finder) {
this.finder = finder;
}
}
- 接口注入
//1.首先要创建一个注入使用的接口。
public interface InjectFinder {
void injectFinder(MovieFinder finder);
}
//2.我们让MovieLister实现这个接口。
class MovieLister implements InjectFinder {
public void injectFinder(MovieFinder finder) {
this.finder = finder;
}
}
//3.我们需要根据不同的框架创建被依赖的MovieFinder的实现