Java Q&A: 使用Factory Method模式

王朝java/jsp·作者佚名  2008-05-31
宽屏版  字体: |||超大  

Java Q&A: 使用Factory Method模式

Q: 阅读 "Polymorphism in its purest form" 一文时,我看到了一个不熟悉的术语 "Factory method"。你能解释一下什么是Factory method并说明如何使用它吗?

A: Factory method(工厂方法)只不过是实例化对象的一种方法的名称。就象工厂一样,Factory method的任务是创建--或制造--对象。

让我们看一个例子。

每个程序要有一种报错的方式。看看下面的接口:

代码清单1

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 );

}

假设写了两个实现。一个实现(代码清单3)将信息写到命令行,另一个(代码清单2)则写到文件中。

代码清单2

public class FileTrace implements Trace {

private java.io.PrintWriter pw;

private boolean debug;

public FileTrace() throws java.io.IOException {

// a real FileTrace would need to oBTain the filename somewhere

// for the example I'll hardcode it

pw = new java.io.PrintWriter( new java.io.FileWriter( "c:race.log" ) );

}

public void setDebug( boolean debug ) {

this.debug = debug;

}

public void debug( String message ) {

if( debug ) { // only print if debug is true

pw.println( "DEBUG: " + message );

pw.flush();

}

}

public void error( String message ) {

// always print out errors

pw.println( "ERROR: " + message );

pw.flush();

}

}

代码清单3

public class SystemTrace implements Trace {

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有