控制反转(Inversion ofControl,英文缩写为IoC)是一种可以解耦的方法,不是什么技术,是一种思想,也是轻量级的Spring框架的核心。控制反转一般分为两种类型,依赖注入(DependencyInjection,简称DI)和依赖查找。控制反转是,关于一个对象如何获取他所依赖的对象的引用,这个责任的反转。
我们通过一个例子体会IoC的好处:
数据模型如下:
Human接口:
package sping.tgb.ioc;
public interface Human {
public void eat();
public void sleep();
}
Student类:
package sping.tgb.ioc;
public class Student implements Human {
public void eat() {
System.out.println("学生吃饭");
}
public void sleep() {
System.out.println("学生睡觉");
}
}
Teacher类:
package sping.tgb.ioc;
public class Teacher implements Human {
public void eat() {
System.out.println("老师吃饭");
}
public void sleep() {
System.out.println("老师睡觉");
}
}
用工厂模式:
我们如果要在客户端调用这两个类,不用控制反转的话,可以用工厂实现,如下:
工厂类:
package sping.tgb.ioc;
public class Factory {
public final static String TEACHER = "teacher";
public final static String STUDENT = "student";
public Human getHuman(String ethnic) {
if (ethnic.equals(TEACHER))
return new Teacher();
else if (ethnic.equals(STUDENT))
return new Student();
else
throw new IllegalArgumentException("参数(职业)错误");
}
}
客户端:
public static void main(String[] args) {
Human human =null;
human=new Factory().getHuman(Factory.STUDENT);
human.eat();
human.sleep();
human=new Factory().getHuman(Factory.TEACHER);
human.eat();
human.sleep();
}
输出结果:
用Spring:
用工厂我们做到了解耦和,客户端不用知道具体的调用类,由工厂判断。下面我们看一下用控制反转我们如何做:
使用spring,我们就不用写工厂类,直接写配置文件,如下:
客户端:
public static void main(String[] args) {
BeanFactory beanFactory=null;
beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml");
Human human = null;
human = (Human) beanFactory.getBean("student");
human.eat();
human.sleep();
human = (Human) beanFactory.getBean("teacher");
human.eat();
human.sleep();
}
输出结果:
对比:
大家可以看到用IoC和用工厂的作用基本是一致的,那为什么还要用IoC呢?优势在哪里?
Spring做到了解耦,上一层不依赖下一层的具体类,同样,工厂也做到了。但是用Spring当需求发生变化时只要修改配置文件,不用重新编译系统;而用工厂当需求发生变化需要增加或删除、修改类时,需要重新编译。这样可以说Spring做到了热插拔。
总结:
IoC的灵活性是有代价的:设置步骤麻烦、生成对象的方式不直观、反射比正常生成对象在效率上慢一点。因此并不是任何地方都适合用IoC的,用到工厂模式的地方都可以考虑用IoC模式。