gpt4 book ai didi

java - 创建文档对象

转载 作者:行者123 更新时间:2023-12-01 14:18:39 26 4
gpt4 key购买 nike

以下是创建 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com