1:看解释器模式,看到下面的代码
Document doc = null; //建立一个解析器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //获得一个DocumentBuilder对象,这个对象代表了具体的DOM解析器 DocumentBuilder builder=factory.newDocumentBuilder(); //得到一个表示XML文档的Document对象 doc=builder.parse(filePathName); //去掉XML文档中作为格式化内容的空白而映射在DOM树中的不必要的Text Node对象 doc.normalize();
DocumentBuilderFactory为抽象类,抽象类一般是不会去实例化的。
这里的DocumentBuilderFactory.newInstance()是使用了抽象类的static方法去返回一个实例,
可以看源码
public static DocumentBuilderFactory newInstance() { try { return (DocumentBuilderFactory) FactoryFinder.find( /* The default property name according to the JAXP spec */ "javax.xml.parsers.DocumentBuilderFactory", /* The fallback implementation class name */ "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); } catch (FactoryFinder.ConfigurationError e) { throw new FactoryConfigurationError(e.getException(), e.getMessage()); } }
这里返回的是FactoryFinder.find,find方法去查找本地的实例类,我们可以通过代码去看下
public class test{ public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); System.out.println(factory); System.out.println(builder); System.out.println(document); } }
输出结果为
com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl@15eb0a9
com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl@1a05308
[#document: null]
而DocumentBuilderFactoryImpl则是
public class DocumentBuilderFactoryImpl extends DocumentBuilderFactory{}
DocumentBuilderImpl则是
public class DocumentBuilderImpl extends DocumentBuilder implements JAXPConstants{}
都是实例化的子类。
2:其实抽象类的newInstance方法一般都定义为static的,使用静态方法返回其子类实例的类。这样做一般就是表明它的子类不应该再扩展其他新的方法了,只需要实现这个抽象类声明的方法就够了。比如内部类
public abstract class Abstract { public static Abstract newInstance() { return new AbstractImpl(); } public abstract void method(String s); protected static class AbstractImpl extends Abstract { public void method(String s) { System.out.println(s); } } public static void main(String [] args){ Abstract abs=Abstract.newInstance(); System.out.println(abs); abs.method("抽象类的newInstance演示"); } }
运行结果为
com.lxw.test.Abstract$AbstractImpl@757aef
抽象类的newInstance演示