java Q&A: 使用Factory Method模式
Q: 閱讀 "Polymorphism in its purest form" 一文時,我看到了一個不熟悉的術(shù)語 "Factory method"。你能解釋一下什么是Factory method并說明如何使用它嗎?
A: Factory method(工廠方法)只不過是實例化對象的一種方法的名稱。就象工廠一樣,F(xiàn)actory method的任務(wù)是創(chuàng)建--或制造--對象。
讓我們看一個例子。
每個程序要有一種報錯的方式。看看下面的接口:
代碼清單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 );
}
假設(shè)寫了兩個實現(xiàn)。一個實現(xiàn)(代碼清單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 {
新聞熱點
疑難解答