Factory模式 利用给Factory对象传递不同的参数以返回具有相同基类或实现了同一接口的对象 Abstract Factory模式 先利用Factory模式返回Factory对象在通过Factory对象返回不同的对象! Java中的例子JAXP 以下是用Simple API for XML(SAX) Parse XML文件的片段 String uri = file: + new File (xmlfilename)getAbsolutePath (); Parser parser; // Abstract Factory模式 SAXParserFactory spf = SAXParserFactorynewInstance (); String validation = SystemgetProperty ( javaxxmlparsersvalidation false); if (validationequalsIgnoreCase(true)) spfsetValidating (true); // Factory模式 SAXParser sp = spfnewSAXParser (); parser = spgetParser (); parsersetDocumentHandler (this); parserparse (uri); SAXParserFactory中的静态方法newInstance()根据系统属性javaxxmlparsersSAXParserFactory不同的值 生成不同的SAXParserFactory对象spf然后SAXParserFactory对象又利用方法newSAXParser()生成SAXParser对象 注意 SAXParserFactory 的定义为 public abstract class SAXParserFactory extends javalangObject SAXParserFactoryImpl 的定义为 public class SAXParserFactoryImpl extends javaxxmlparsersSAXParserFactory public static SAXParserFactory newInstance() { String factoryImplName = null; try { factoryImplName = SystemgetProperty(javaxxmlparsersSAXParserFactory comsunxmlparserSAXParserFactoryImpl); }catch (SecurityException se) { factoryImplName = comsunxmlparserSAXParserFactoryImpl; } SAXParserFactory factoryImpl; try { Class clazz = ClassforName(factoryImplName); factoryImpl = (SAXParserFactory)clazznewInstance(); }catch(ClassNotFoundException cnfe) { throw new FactoryConfigurationError(cnfe); } catch (IllegalAccessException iae) { throw new FactoryConfigurationError(iae); } catch (InstantiationException ie) { throw new FactoryConfigurationError(ie); } return factoryImpl; } newSAXParser()方法在SAXParserFactory定义为抽象方法 SAXParserFactoryImpl继承了SAXParserFactory它实现了方法newSAXParser() public SAXParser newSAXParser() throws SAXException ParserConfigurationException { SAXParserImpl saxParserImpl = new SAXParserImpl (this); return saxParserImpl; } 注意 SAXParserImpl的定义为 public class SAXParserImpl extends javaxxmlparsersSAXParser SAXParserImpl的构造函数定义为 SAXParserImpl (SAXParserFactory spf) throws SAXException ParserConfigurationException { super(); thisspf = spf; if (spfisValidating ()) { parser = new ValidatingParser(); validating = true; } else { parser = new Parser(); } if (spfisNamespaceAware ()) { namespaceAware = true; throw new ParserConfigurationException (Namespace not supported by SAXParser); } } 本例子中用到的class和interface的类关系图如下 |