解析器实现中 Document 的功能
最近我正在研究解析器,包括用于构建解析器的设计模式。我选择的示例是 javax.xml.parsers 和 org.w3c.dom 包。
看起来像工厂和构建器模式用于设计这些包中的解析器结构。 DocumentBuilderFactory是返回一个直接工厂来构建DocumentBuilder。然后,DocumentBuilder 使用其 parse() 方法来解析 xml 文件;但在本例中返回类型是 Document: Document doc = builder.parse(in);
但是,我在这里没有得到的是 Document 是一个接口,其中包含大量操作 XML 属性的方法。它还扩展了 Node 接口。我们仍然可以调用它的操作: doc.hasAttributes() 或 doc.getChildNodes() 等。
我花了一个小时在这上面,但仍然无法理解背后的逻辑这种架构:
1)那些 Document 的方法在哪里实现?
2)为什么解析后最好返回接口类型对象(Document)来表示DOM对象?
Recently I was studying about parsers including the design patterns used to built one. The example I have chosen is javax.xml.parsers and org.w3c.dom packages.
Looks like factory and builder patterns used to design the parser structure in these packages. DocumentBuilderFactory is to return an immediate factory to build DocumentBuilder. DocumentBuilder, then, uses its parse() method to parse an xml file; but the return type is Document in this case: Document doc = builder.parse(in);
But, what I didn't get here is Document is an interface which contains plenty of methods to manipulate XML attributes. It also extends Node interface. We can still call its operations: doc.hasAttributes()
or doc.getChildNodes()
etc.
I spent an hour on this, but still couldn't get the logic behind this architecture:
1) Where are those Document's methods implemented?
2) Why is it better to return interface type object (Document) to represent the DOM object after parsing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Document
、Node
、Element
和所有其他类型都是接口。有几个库为这些接口提供了实现 - 一个突出的例子是 Apache Xerces。从他们的首页:如果您确实需要知道实际使用了哪个 DOM 实现,请启动调试器或将
Document
对象的类名转储到控制台/日志。Document
,Node
,Element
and all of the other types are interfaces. There are a couple of libraries around that provide an implementation for those interfaces - one prominent example is Apache Xerces. From their front page:If you exactly need to know which implementation of DOM is actually used, start a debugger or dump the class name of your
Document
object to the console/log.您在 DocumentBuilderFactory javadoc 上拥有获取真实类 DocumentBuilderFactory 的策略,以及所有其他内容,位于 公共静态 DocumentBuilderFactory newInstance()。
You have, on the DocumentBuilderFactory javadoc, the policy to get the real class DocumentBuilderFactory, and all the rest, at public static DocumentBuilderFactory newInstance().