WEB开发网
开发学院WEB开发Jsp Java深入分析之:使用FactoryMethod模式 阅读

Java深入分析之:使用FactoryMethod模式

 2008-01-05 09:43:00 来源:WEB开发网   
核心提示:阅读 "Polymorphism in its purest form" 一文时,我看到了一个不熟悉的术语 "Factory method",Java深入分析之:使用FactoryMethod模式,你能解释一下什么是Factory method并说明如何使用它吗?A: Facto

  阅读 "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:\trace.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 {
  
  private boolean debug;
  
  public void setDebug( boolean debug ) {
  this.debug = debug;
  }
  
  public void debug( String message ) {
  if( debug ) { // only print if debug is true
  System.out.println( "DEBUG: " + message );
  }
  }
  public void error( String message ) {
  // always print out errors
  System.out.println( "ERROR: " + message );
  }
  
  }
  
  要使用这两个类中的任一个,需要这样做:
  
  代码清单4
  
  //... some code ...
  SystemTrace log = new SystemTrace();
  //... code ...
  log.debug( "entering loog" );
  // ... etc ...
  
  现在,假如想改变程序中用到的 "Trace实现",就需要修改实例化 "Trace实现" 的每个类。使用了Trace的类的数量可能很多,这种修改就需要大量的工作。而且,你一定也想尽可能地避免大量修改你的类。
  
  代码清单5
  
  public class TraceFactory {
  public static Trace getTrace() {
  return new SystemTrace();
  }
  }
  
  getTrace()是一个Factory method。这样,无论什么时候你想得到一个Trace的引用,只用简单地调用TraceFactory.getTrace():
  
  代码清单6
  
  //... some code ...
  Trace log = new TraceFactory.getTrace();

Tags:Java 深入 分析

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接