Spring核心之IOC

时间:2024-05-14 18:04:56

IOC是Spring的两大核心之一:IOC的核心就是解耦。

  举个例子:有2个班级可以上课,校长指定老师去上课,代码如下

  

package com.hongcong.test;

public class Class1 {
public void teach(){
System.out.println("一班在上课");
}
}
package com.hongcong.test;

public class Class2  {
public void teach(){
System.out.println("二班在上课");
}
}

teacher

package com.hongcong.test;

public class teacher {

    public void doTeach(){
Class1 class1 = new Class1();
class1.teach(); }
}

校长

package com.hongcong.service;

import com.hongcong.test.Class1;
import com.hongcong.test.Class2;
import com.hongcong.test.teacher; public class Principal {
public static void main(String[] args) {
teacher teacher = new teacher();
teacher.doTeach(); }
}

这时候去执行校长时,一班就开始上课了。但是如果校长想要老师去二班上课的话,要么修改老师中的方法;要么新增老师的方法且修改校长中的方法。可以看出,此时的代码耦合在了一起。这时候可以借助IOC的思想去重新设计这个程序,代码如下:

定义一个上课的接口,然后班级一和班级二都去实现这个接口:

package com.hongcong.test;

public interface TeachInterface {
public void teach();
}
package com.hongcong.test;

public class Class1 implements TeachInterface{
public void teach(){
System.out.println("一班在上课");
}
}
package com.hongcong.test;

public class Class2 implements TeachInterface{
public void teach(){
System.out.println("二班在上课");
}
}
package com.hongcong.test;

public class teacher {
private TeachInterface teachInterface; public void setTeachInterface(TeachInterface teachInterface) {
this.teachInterface = teachInterface;
} public void doTeach(){ teachInterface.teach();
}
}
package com.hongcong.service;

import com.hongcong.test.Class1;
import com.hongcong.test.Class2;
import com.hongcong.test.teacher; public class Principal {
public static void main(String[] args) { teacher teacher = new teacher();
teacher.setTeachInterface(new Class2());
teacher.doTeach();
}
}

此时校长如果想让老师去一班上课,只需要修改teacher.setTeachInterface(new Class2());方法中的参数就可以了。老师已经和去哪个班级上课完全没有关系了,只要校长下个指令就行。