Factory Method pattern工厂方法模式
当client不知道要创建哪个具体类的实例,或者不想在client代码中指明要具体创建的实例时,用工厂方法。定义一个用于创建对象的接口,让其子类来决定实例化哪一个类,从而使一个类的实例化延迟到其子类。
代码示例:
有个抽象产品;
public interface Trace {
// turn on and off debugging
public void setDebug( boolean debug );
// write out a debug message
public void debug( String message );
// write out an error message
public void error( String message );
}
具体的产品类FileTrace:
public class FileTrace implements Trace {
private PrintWriter pw;
private boolean debug;
public FileTrace() throws IOException {
pw = new PrintWriter( new FileWriter( "t.log" ) );
}
public void setDebug( boolean debug ) {
this.debug = debug;
}
public void debug( String message ) {
if( debug ) {
pw.println( "DEBUG: " + message );
pw.flush();
}
}
public void error( String message ) {
pw.println( "ERROR: " + message );
pw.flush();
}
}
具体的产品类SystemTrace:
public class SystemTrace implements Trace {
private boolean debug;
public void setDebug( boolean debug ) {
this.debug = debug;
}
public void debug( String message ) {
if( debug )
System.out.println( "DEBUG: " + message );
}
public void error( String message ) {
System.out.println( "ERROR: " + message );
}
}
客户端使用:
Trace log = new SystemTrace();
log.debug( "entering log" );
Trace log2 = new FileTrace();
log.debug(“...”);
使用工厂模式:
先定义工厂接口:
interface TraceFactory {
public Trace getTrace();//factory method
public Trace getTrace(String type);//factory method
void otherOperation(){};//还可以实现其他功能
}
实现工厂接口:
public class Factory1 implements TraceFactory {
public Trace getTrace() {
return new SystemTrace();
}
}
根据类型决定创建哪个具体产品
public class Factory2 implements TraceFactory {
public getTrace(String type) {
if(type.equals(“file”)
return new FileTrace();
else if (type.equals(“system”)
return new SystemTrace();
}
Client使用“工厂方法”来创建实例,得到实例的类型是抽象接口,而非具体类
Trace log1 = new Factory1().getTrace();
log1.setDebug(true);
log1.debug( "entering log" );
Trace log2 = new Factory2().getTrace("system");
log2.setDebug(false);
log2.debug("...");
如果用静态工厂方法,既可以在ADT内部实现,也可以构造单独的工厂类:
public class TraceFactory1 {
public static Trace getTrace() {
return new SystemTrace();
}
}
public class TraceFactory2 {
public static Trace getTrace(String type) {
if(type.equals(“file”)
return new FileTrace();
else if (type.equals(“system”)
return new SystemTrace();
}
}
客户端:
Trace log1 = TraceFactory1.getTrace();
log1.setDebug(true);
log1.debug( "entering log" );
Trace log2 = TraceFactory2.getTrace(“system”);
log1.setDebug(true);
log2.debug(“...”)