factory模式
利用给factory对象传递不同的参数,以返回具有相同基类或实现了同一接口的对象。
abstract factory模式
先利用factory模式返回factory对象,在通过factory对象返回不同的对象!
java中的例子-----jaxp1.0.1 :
以下是用simple api for xml(sax) parse xml文件的片段
...
string uri = "file:" + new file (xmlfilename).getabsolutepath ();
parser parser;
//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 class saxparserfactoryimpl extends javax.xml.parsers.saxparserfactory
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的构造函数定义为:
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");
}
}
本例子中用到的class和interface的类关系图如下
闽公网安备 35060202000074号