控制反转思想的理解实例
通过依赖注入来从不同的部门获取数据,借助其来理解Spring的IOC
package com.xl.ioc.demo; public interface DataManagement { //使用该方法来获取数据 public void getData(); }
package com.xl.ioc.demo; public class DepartmentAData implements DataManagement { @Override public void getData() { //使用该方法来从部门A获取数据 System.out.println("======从部门A获取数据========"); } }
package com.xl.ioc.demo; public class DepartmentBData implements DataManagement { @Override public void getData() { //使用该方法来从部门B获取数据 System.out.println("======从部门B获取数据========"); } }
package com.xl.ioc.demo; public class DepartmentCData implements DataManagement { @Override public 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(); } }