[java] 解析xml文档
思路
- 工厂模式时,常将类名放在xml文档中,实现配置与框架的解耦
代码
AbstractFactoryTest.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class AbstractFactoryTest 2 { 3 public static void main(String[] args) 4 { 5 try 6 { 7 Product a; 8 AbstractFactory af; 9 af=(AbstractFactory) ReadXML1.getObject(); 10 a=af.newProduct(); 11 a.show(); 12 } 13 catch(Exception e) 14 { 15 System.out.println(e.getMessage()); 16 } 17 } 18 } 19 //抽象产品:提供了产品的接口 20 interface Product 21 { 22 public void show(); 23 } 24 //具体产品1:实现抽象产品中的抽象方法 25 class ConcreteProduct1 implements Product 26 { 27 public void show() 28 { 29 System.out.println("具体产品1显示..."); 30 } 31 } 32 //具体产品2:实现抽象产品中的抽象方法 33 class ConcreteProduct2 implements Product 34 { 35 public void show() 36 { 37 System.out.println("具体产品2显示..."); 38 } 39 } 40 //抽象工厂:提供了厂品的生成方法 41 interface AbstractFactory 42 { 43 public Product newProduct(); 44 } 45 //具体工厂1:实现了厂品的生成方法 46 class ConcreteFactory1 implements AbstractFactory 47 { 48 public Product newProduct() 49 { 50 System.out.println("具体工厂1生成-->具体产品1..."); 51 return new ConcreteProduct1(); 52 } 53 } 54 //具体工厂2:实现了厂品的生成方法 55 class ConcreteFactory2 implements AbstractFactory 56 { 57 public Product newProduct() 58 { 59 System.out.println("具体工厂2生成-->具体产品2..."); 60 return new ConcreteProduct2(); 61 } 62 }
ReadXML1.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import javax.xml.parsers.*; 2 import org.w3c.dom.*; 3 import java.io.*; 4 class ReadXML1 5 { 6 //该方法用于从XML配置文件中提取具体类类名,并返回一个实例对象 7 public static Object getObject() 8 { 9 try 10 { 11 //创建文档对象 12 DocumentBuilderFactory dFactory=DocumentBuilderFactory.newInstance(); 13 DocumentBuilder builder=dFactory.newDocumentBuilder(); 14 Document doc; 15 doc=builder.parse(new File("src/config1.xml")); 16 //获取包含类名的文本节点 17 NodeList nl=doc.getElementsByTagName("className"); 18 Node classNode=nl.item(0).getFirstChild(); 19 String cName=classNode.getNodeValue(); 20 //System.out.println("新类名:"+cName); 21 //通过类名生成实例对象并将其返回 22 Class<?> c=Class.forName(cName); 23 Object obj=c.newInstance(); 24 return obj; 25 } 26 catch(Exception e) 27 { 28 e.printStackTrace(); 29 return null; 30 } 31 } 32 }
config1.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <config> 3 <className>ConcreteFactory1</className> 4 </config>
具体工厂1生成-->具体产品1...
具体产品1显示...