📚相关专栏:程序猿的春天
一、IOC(Inversion of Control)
1、概念
IOC(Inversion of Control,控制反转)是一种设计原则,它将对象的控制权从程序代码中转移到外部容器中。比如在类上⾯添加 @RestController 和 @Controller 注解,就是把这个对象交给Spring管理,Spring 框架启动时就会加载该类。把对象交给Spring管理,就是IoC思想。
2、具体分析
比如我们有一个需求是:造一辆车
(1)传统开发过程
先设计轮⼦(Tire),然后根据轮⼦的⼤⼩设计底盘(Bottom),接着根据底盘设计⻋⾝(Framework),最后根据⻋⾝设计好整个汽⻋(Car)。这⾥就出现了⼀个"依赖"关系:汽⻋依赖⻋⾝,⻋⾝依赖底盘,底盘依赖轮⼦
代码如下:
public class CarExample {
public static void main(String[] args) {
Car car = new Car();
car.run();
}
/**
* 汽⻋对象
*/
static class Car {
private Framework framework;
public Car() {
framework = new Framework();
System.out.println("Car init....");
}
public void run(){
System.out.println("Car run...");
}
}
/**
* ⻋⾝类
*/
static class Framework {
private Bottom bottom;
public Framework() {
bottom = new Bottom();
System.out.println("Framework init...");
}
}
/**
* 底盘类
*/
static class Bottom {
private Tire tire;
public Bottom() {
this.tire = new Tire();
System.out.println("Bottom init...");
}
}
/**
* 轮胎类
*/
static class Tire {
// 尺⼨
private int size;
public Tire(){
this.size = 17;
System.out.println("轮胎尺⼨:" + size);
}
}
}
这样设计确实可以实现我们的需求。但是可维护性非常低。当我们需要更改某一个需求时,就很有可能会“牵一发而动全身”。
比如当我们需要定制各种尺寸的轮胎时,轮胎的尺寸就需要修改为变量:
但是由于这种开发方式的耦合调用关系,只改轮胎的代码肯定会导致其它依赖的程序出现报错,就需要继续修改:
由以上例子我们不难看出,传统的开发方式各个类的耦合程度过高,各个类直接相互依赖,当某个类需要发生改变时,整个调⽤链上的所有代码都需要修改
(2)IOC开发方式
我们可以先设计汽⻋的⼤概样⼦,然后根据汽⻋的样⼦来设计⻋⾝,根据⻋⾝来设计底盘ÿ