Java 常用API的运用,效率及技巧十一

xiaoxiao2021-03-01  4

常用设计模式

1Singleton模式

Singleton模式主要作用是保证在Java应用程序中,一个Class只有一个实例存在。一般有两种方法:

Ø  定义一个类,它的构造函数为private的,所有方法为static的。其他类对它的引用全部是通过类名直接引用。例如:

private SingleClass() {}

public static String getMethod1() {}

public static ArrayList getMethod2() {}

Ø  定义一个类,它的构造函数为private的,它有一个staticprivate的该类变量,通过一个publicgetInstance方法获取对它的引用,继而调用其中的方法。例如:

private staitc SingleClass _instance = null; private SingleClass() {} public static SingleClass getInstance() { if (_instance == null) { _instance = new SingleClass(); } return _instance; } public String getMethod1() {} public ArrayList getMethod2() {}

 

 

// 1. Abstract Factory模式 SAXParserFactory spf = SAXParserFactory.newInstance(); String validation = System.getProperty ( "javax.xml.parsers.validation", "false"); if (validation.equalsIgnoreCase("true")) { spf.setValidating (true); } // 2. Factory模式 SAXParser sp = spf.newSAXParser(); parser = sp.getParser(); parser.setDocumentHandler(this); parser.parse (uri);

  

1. SAXParserFactory中的静态方法newInstance()根据系统属性javax.xml.parsers.SAXParserFactory不同的值生成不同的SAXParserFactory对象spf。然后SAXParserFactory对象又利用方法newSAXParser()生成SAXParser对象。

注意:

SAXParserFactory 的定义为:

public abstract class SAXParserFactory extends java.lang.Object

SAXParserFactoryImpl 的定义为:

public static SAXParserFactory newInstance() { String factoryImplName = null; try { factoryImplName = System.getProperty("javax.xml.parsers.SAXParserFactory", "com.sun.xml.parser.SAXParserFactoryImpl"); } catch (SecurityException se) { factoryImplName = "com.sun.xml.parser.SAXParserFactoryImpl"; } SAXParserFactory factoryImpl; try { Class clazz = Class.forName(factoryImplName); factoryImpl = (SAXParserFactory) clazz.newInstance(); } catch (ClassNotFoundException cnfe) { throw new FactoryConfigurationError(cnfe); } catch (IllegalAccessException iae) { throw new FactoryConfigurationError(iae); } catch (InstantiationException ie) { throw new FactoryConfigurationError(ie); } return factoryImpl; }

  

2. newSAXParser() 方法在SAXParserFactory定义为抽象方法,

SAXParserFactoryImpl继承了SAXParserFactory,它实现了方法newSAXParser()

public SAXParser newSAXParser() throws SAXException, ParserConfigurationException { SAXParserImpl saxParserImpl = new SAXParserImpl(this); return saxParserImpl; }

 

注意:

SAXParserImpl的定义为:

public class SAXParserImpl extends javax.xml.parsers.SAXParser

SAXParserImpl的构造函数定义为:

public SAXParserImpl(SAXParserFactory spf) throws SAXException, ParserConfigurationException { super(); this.spf = spf; if (spf.isValidating ()) { parser = new ValidatingParser(); validating = true; } else { parser = new Parser(); } if (spf.isNamespaceAware ()) { namespaceAware = true; throw new ParserConfigurationException( "Namespace not supported by SAXParser"); } }

  

相关资源:Java 面经手册·小傅哥(公众号:bugstack虫洞栈).pdf
转载请注明原文地址: https://www.6miu.com/read-3100286.html

最新回复(0)