設計模式(9)----- 補充spring中的工廠設計模式(手寫)
阿新 • • 發佈:2018-11-05
package com.DesignPatterns.ad.factory6; public interface BeanFactory { Object getBean(String id); }
package com.DesignPatterns.ad.factory6; public interface Moveable { void run(); }
package com.DesignPatterns.ad.factory6; public class Car implements Moveable{public void run() { System.out.println("冒著煙奔跑中car......."); } }
package com.DesignPatterns.ad.factory6; public class Train implements Moveable{ @Override public void run() { System.out.println("小火車嗚嗚嗚"); } }
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="v" class="com.DesignPatterns.ad.factory6.Train"> </bean> <bean id="n" class="com.DesignPatterns.ad.factory6.Car"> </bean> <!-- //v=com.bjsxt.spring.factory.Car --> </beans>
package com.DesignPatterns.ad.factory6; 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{ //解析xml的不用太關心這裡。主要是理解spring的bean的工廠機制。 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(); //最關鍵的就是在這把它的id和物件全部放到一個map中來,所謂的容器其實就是一個map, //當專案啟動的時候就會把所有的在xml配置檔案中配置的物件全部都載入一遍,等用到的時候就會從map中取出來 // container.put(id, o); System.out.println(id + " " + clazz); } } @Override public Object getBean(String id) { return container.get(id); } }
package com.DesignPatterns.ad.factory6; 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/DesignPatterns/ad/factory6/applicationContext.xml"); //這裡就和我們平常用的set注入進來的目的是一樣的。 Object o1 = f.getBean("v"); Moveable m = (Moveable)o1; m.run(); Object o2 = f.getBean("n"); Moveable n = (Moveable)o2; n.run(); } }
只需要修改配置檔案就可以實現注入的邏輯。建立物件是不是變的更加簡單了好多。
它的原理就是通過獲取xml中class的字串的路徑,然後在通過反射獲取物件,最後在使用這個物件,這樣就免去了來回new物件產生的不必要的剪不斷理還亂的物件的依賴的關係。