[Java] 设计模式之工厂系列 04 (自定义模拟 spring 读取xml文件 beanFactory)
Moveable
package com.bjsxt.spring.factory; public interface Moveable { void run(); }Car
package com.bjsxt.spring.factory; public class Car implements Moveable { public void run() { System.out.println("冒着烟奔跑中car......."); } }Train
package com.bjsxt.spring.factory; public class Train implements Moveable { @Override public void run() { System.out.println("小火车呜呜呜"); } }BeanFactory
package com.bjsxt.spring.factory; public interface BeanFactory { Object getBean(String id); }ClassPathXmlApplicationContext
package com.bjsxt.spring.factory; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; public class ClassPathXmlApplicationContext implements BeanFactory { private Map<String, Object> container = new HashMap<String, Object>(); public ClassPathXmlApplicationContext(String fileName) throws Exception{ SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(this.getClass().getClassLoader() .getResourceAsStream(fileName)); Element root = doc.getRootElement(); List list = XPath.selectNodes(root, "/beans/bean"); System.out.println(list.size()); for (int i = 0; i < list.size(); i++) { Element bean = (Element) list.get(i); String id = bean.getAttributeValue("id"); String clazz = bean.getAttributeValue("class"); Object o = Class.forName(clazz).newInstance(); container.put(id, o); System.out.println(id + " " + clazz); } } @Override public Object getBean(String id) { return container.get(id); } }applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="v" class="com.bjsxt.spring.factory.Train"> </bean> <!-- //v=com.bjsxt.spring.factory.Car --> </beans>Test
package com.bjsxt.spring.factory; import java.io.IOException; import java.util.Properties; public class Test { /** * @param args * @throws IOException */ public static void main(String[] args) throws Exception { BeanFactory f = new ClassPathXmlApplicationContext("com/bjsxt/spring/factory/applicationContext.xml"); Object o = f.getBean("v"); Moveable m = (Moveable)o; m.run(); } }