ioc控制反转_spring新手入门(二):IOC控制反转

IOC(控制反转):全称为:Inverse of Control,将程序中组建的依赖关系由程序维护改为通过配置来维护,实现对象之间的松耦合。

以下举一个例子来说明IOC。

比如一个person类,人具有穿衣服的属性,可以穿T恤,衬衫,裙子等。

我们用程序来实现该段描述:

方式一:手工维护对象之间的关系

新建person类,由于person具有穿T恤,衬衫,裙子等动作,所以再新建一个接口Clothes,穿裙子,T恤,衬衫等实现该接口,裙子,T恤,衬衫等

person类:

8af39adb0ed3eae14d2bf0fee65584a7.png

Clothes接口:

0b5804a55e1d9b092645a16c413f9b87.png

T恤实现类:

b32002e67a48c73d2f8ffec36fa552c1.png

裙子实现类:

6827cca76a4ae054d8452d6859a46a1f.png

衬衫实现类:

6302fc87aae54c7468caebd4c1363c10.png

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();

70313150e1fcc480167133b72efc500c.png

执行结果

每当增一个Person对象,他有穿衣服的需求,那么程序就需要再去new一个clothes对象,当对象不断增加后,程序就变得很难维护了。

方式二:使用spring IOC容器:

Spring IOC容器可以非常方便完成对象的创建和依赖的管理注入,通过对bean的配置,原来需要通过代码来new对象的工作完全交由IOC容器去维护,这样就实现了控制反转,从业务层面上也解耦了。(比如本例中的person与clothes)。

Bean配置:建立person与Tshirt,Skirt,Shirt之间的关系。

791b69d692d5c4ac8acefdb796e3eced.png

通过读取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();
eedd3c9d742fd7f96dd5caa34f5dc083.png

执行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值