Factory模式
利用給Factory對象傳遞不同的參數
Abstract Factory模式
先利用Factory模式返回Factory對象
Java中的例子
以下是用Simple API for XML(SAX) Parse XML文件的片段
String uri =
Parser parser;
//
SAXParserFactory spf = SAXParserFactory
String validation = System
if (validation
spf
//
SAXParser sp = spf
parser = sp
parser
parser
生成不同的SAXParserFactory對象spf
注意
SAXParserFactory 的定義為
public abstract class SAXParserFactory extends java
SAXParserFactoryImpl 的定義為
public class SAXParserFactoryImpl extends javax
public static SAXParserFactory newInstance() {
String factoryImplName = null;
try {
factoryImplName =
System
}catch (SecurityException se) {
factoryImplName =
}
SAXParserFactory factoryImpl;
try {
Class clazz = Class
factoryImpl = (SAXParserFactory)clazz
}catch (ClassNotFoundException cnfe) {
throw new FactoryConfigurationError(cnfe);
} catch (IllegalAccessException iae) {
throw new FactoryConfigurationError(iae);
} catch (InstantiationException ie) {
throw new FactoryConfigurationError(ie);
}
return factoryImpl;
}
SAXParserFactoryImpl繼承了SAXParserFactory
public SAXParser newSAXParser() throws SAXException
ParserConfigurationException
{
SAXParserImpl saxParserImpl = new SAXParserImpl (this);
return saxParserImpl;
}
注意
SAXParserImpl的定義為
public class SAXParserImpl extends javax
SAXParserImpl的構造函數定義為
SAXParserImpl (SAXParserFactory spf) throws SAXException
ParserConfigurationException
{
super();
this
if (spf
parser = new ValidatingParser();
validating = true;
}
else {
parser = new Parser();
}
if (spf
namespaceAware = true;
throw new ParserConfigurationException
(
}
}
本例子中用到的class和interface的類關系圖如下
From:http://tw.wingwit.com/Article/program/Java/gj/201311/11158.html