IOC(控制反转):全称为:Inverse of Control,将程序中组建的依赖关系由程序维护改为通过配置来维护,实现对象之间的松耦合。
以下举一个例子来说明IOC。
比如一个person类,人具有穿衣服的属性,可以穿T恤,衬衫,裙子等。
我们用程序来实现该段描述:
方式一:手工维护对象之间的关系
新建person类,由于person具有穿T恤,衬衫,裙子等动作,所以再新建一个接口Clothes,穿裙子,T恤,衬衫等实现该接口,裙子,T恤,衬衫等
person类:
Clothes接口:
T恤实现类:
裙子实现类:
衬衫实现类:
person 穿衬衫,裙子,T恤
Person girl = new Person();
girl.setClothes(new Skirt());
girl.getClothes();
/Person使用Shirt
Person man = new Person();
man.setClothes(new Shirt());
man.getClothes();
/Person使用Tshirt
Person young = new Person();
young.setClothes(new Tshirt());
young.getClothes();
每当增一个Person对象,他有穿衣服的需求,那么程序就需要再去new一个clothes对象,当对象不断增加后,程序就变得很难维护了。
方式二:使用spring IOC容器:
Spring IOC容器可以非常方便完成对象的创建和依赖的管理注入,通过对bean的配置,原来需要通过代码来new对象的工作完全交由IOC容器去维护,这样就实现了控制反转,从业务层面上也解耦了。(比如本例中的person与clothes)。
Bean配置:建立person与Tshirt,Skirt,Shirt之间的关系。
通过读取spring-config.xml配置文件,由IOC容器帮助生成对象,效果与“方式一:手工维护”完全一样。
public static void main(String[] args){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml"); Person girl = (Person)applicationContext.getBean("girl"); girl.getClothes(); Person man = (Person)applicationContext.getBean("man"); man.getClothes(); Person young = (Person)applicationContext.getBean("young"); young.getClothes();