控制反转思想的理解实例

来源:互联网 发布:mac电脑铃声剪辑软件 编辑:程序博客网 时间:2024/06/01 12:33
 
通过依赖注入来从不同的部门获取数据,借助其来理解Spring的IOC
package com.xl.ioc.demo;public interface DataManagement {//使用该方法来获取数据public void getData();}

package com.xl.ioc.demo;public class DepartmentAData implements DataManagement {@Overridepublic void getData() {//使用该方法来从部门A获取数据System.out.println("======从部门A获取数据========");}}


 

package com.xl.ioc.demo;public class DepartmentBData implements DataManagement {@Overridepublic void getData() {//使用该方法来从部门B获取数据System.out.println("======从部门B获取数据========");}}


 

package com.xl.ioc.demo;public class DepartmentCData implements DataManagement {@Overridepublic void getData() {//使用该方法来从部门C获取数据System.out.println("======从部门C获取数据========");}}


 

package com.xl.ioc.demo;public class Business {private DataManagement dm;public void setDm(DataManagement dm) {this.dm = dm;}//根据注入的获取数据public void getData() {dm.getData();}}


 

package com.xl.ioc.demo;public class Test {public static void main(String[] args) {Business business = new Business();//business.setDm(new DepartmentAData());//business.setDm(new DepartmentBData());business.setDm(new DepartmentCData());business.getData();}}


 

原创粉丝点击