控制反转(
IoC = Inversion of Control ),即用容器控制程序间的(关联、继承等)关系。IoC的目标是为了提升组件重用,降低耦合。 下面用一个简单的例子说明其用途。 1、接口: public interface Action { public String execute(String msg); } 2、子类: public class UpperAction implements Action{ @Override public String execute(String msg) { return "Upper : " + msg.toUpperCase(); } } public class LowerAction implements Action { @Override public String execute(String msg) { return "Lower : " + msg.toLowerCase(); } } 3、容器: import java.util.HashMap; import java.util.Map; public class BeanFactory { private Map<String, String> mapping = new HashMap<String, String>(); public BeanFactory() { refresh(); } /** * 读取配置文件,缓存所有的bean */ private void refresh() { mapping.put("1", "test.ioc.UpperAction"); mapping.put("2", "test.ioc.LowerAction"); // cacheBean("1", "test.ioc.UpperAction"); // cacheBean("2", "test.ioc.LowerAction"); } public Object getInstance(String className) { Class<?> clazz = null; Object obj = null; try { clazz = Class.forName(className); obj = clazz.newInstance(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return obj; } public Object cacheBean(String id, String className) { if(!mapping.containsKey(id)) { mapping.put(id, className); } return getInstance(className); } public Object getBean(String id) { Object obj = cacheBean(id, mapping.get(id)); if(obj == null) { System.out.println("没有找到相关的bean..."); } return obj; } } 4、测试用例: public class TestCase { public static void main(String[] args) { BeanFactory ioc = new BeanFactory(); Action action = (Action) ioc.getBean("1"); System.out.println(action.execute("hahahHHH")); } } |
|