java - 创建文档对象

标签 java design-patterns dom

以下是创建 Document 对象的步骤:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

我有几个问题:

  1. 为什么我们需要 DocumentBuilderFactory?拥有一个 DocumentBuilder 来创建文档还不够吗? (假设几个构造函数还不够)

  2. newDocumentBuilder是一个抽象方法。怎么称呼?

  3. 这里使用了哪些设计模式以及它们的作用是什么?

最佳答案

DocumentBuilderFactory 是一个抽象类。这并不意味着您不能调用属于该类的静态方法。

看看这里 DocumentBuilderFactory.newInstance() 到底做了什么。

http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#newInstance()

Obtain a new instance of a DocumentBuilderFactory. This static method creates a new factory instance. This method uses the following ordered lookup procedure to determine the DocumentBuilderFactory implementation class to load:

  1. Use the javax.xml.parsers.DocumentBuilderFactory system property.
  2. Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JAXP implementation and it's values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.
  3. Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.parsers.DocumentBuilderFactory in jars available to the runtime.
  4. Platform default DocumentBuilderFactory instance.

Once an application has obtained a reference to a DocumentBuilderFactory it can use the factory to configure and obtain parser instances.

现在您知道工厂如何尝试加载正确的类了。 newInstance() 返回的实例将是 DocumentBuilderFactory 的实现。此实现实现了抽象方法 * newDocumentBuilder* ,它将为给定的实现创建文档生成器。

很明显这里使用了工厂模式。

关于java - 创建文档对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17853318/

相关文章:

javascript - 在 jQuery 选择器中混合逻辑 AND 和 OR

java - 查找小于 n 的最大平方数的算法

java - 如何在java中创建ArrayList数组?

c++ - 将 NSNotificationCenter 设计模式移动到 C++ 进行移植?

java - java中如何实现模式匹配,避免instanceof?

design-patterns - DAO 是否负责向 'join' 表中插入记录

javascript - 如何保存范围对象(来自 getSelection),以便我可以在不同的页面加载上重现它?

javascript - 将元素插入 DOM,基于时间戳的位置

java - 如何使用 xAgent 读取 RSS 提要?

java - 如何使用 GeoTools 和拓扑集成地理编码和引用线文件进行地理编码