IOC vs DI vs DIP

先说结论
DI < IOC $\approx$ DIP

DIP 依赖反转原则 IOC 控制反转

ass
图1高层对象A依赖于底层对象B的实现;图2中,把高层对象A对底层对象的需求抽象为一个接口A,底层对象B实现了接口A,这就是依赖反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class shape {
public:
virtual double get_area() const = 0;
};

class Rectangle: public shape {
public:
double h;
double w;
double get_area() const {
return h * w;
}
};

class Disk: public shape{
public:
double radius;
double get_area() const {
return 3.1415926 * radius * radius;
}
};

class Viewer{
public:
void show_area(const shape & sp){
std::cout << sp.get_area() << std::endl;
}
};

int main(){
Viewer view;
Rectangle rect;
rect.h = 1;
rect.w = 2;
Disk disk;
disk.radius = 3;
view.show_area(disk);
view.show_area(rect);
}

Java 里interface 可以用interface key word 或者abstract class key word来实现, 两者的区别在于

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
interface shape{
public double get_area();
}

class Rectangle implements shape{
double h;
double w;
public double get_area(){
return h * w;
}
}

class Disk implements shape{
double r;
public double get_area(){
return 3.1415926 * r * r;
}
}

class Viewer {
public void show_area(shape sp){
System.out.println(sp.get_area());
}
}

public class testPackage {
public static void main(String[] args) {
Viewer view = new Viewer();
Disk disk = new Disk();
Rectangle rect = new Rectangle();
rect.h = 1;
rect.w = 2;
disk.r = 3;
view.show_area(rect);
view.show_area(disk);
}
}

控制反转与依赖反转本身是十分相似的,但是IOC更进一步要解决Viewer class 直接私有一个shape 对象的例子.

Answering only the first part. What is it?

Inversion of Control (IoC) means to create instances of dependencies first and latter instance of a class (optionally injecting them through constructor), instead of creating an instance of the class first and then the class instance creating instances of dependencies. Thus, inversion of control inverts the flow of control of the program. Instead of the callee controlling the flow of control (while creating dependencies), the caller controls the flow of control of the program.