控制反轉(zhuǎn)(
IoC = Inversion of Control ),即用容器控制程序間的(關(guān)聯(lián)、繼承等)關(guān)系。IoC的目標(biāo)是為了提升組件重用,降低耦合。 下面用一個(gè)簡(jiǎn)單的例子說(shuō)明其用途。 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("沒(méi)有找到相關(guān)的bean..."); } return obj; } } 4、測(cè)試用例: 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")); } } |
|