Java Q&A: 使用Factory Method模式(转)

发布时间: 2007-05-21 09:44    作者: 未知    来源: 未知    浏览:    评论

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:\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();
//... code ...
log.debug( "entering loog" );
// ... etc ...

使用Factory method来获得实例可以大量节省以后的工作。上面的代码中,TraceFactory返回的是SystemTrace实例。假设需求发生了变化,需要将信息写到文件中。如果是使用Factory method来获得实例,只用在一个类中修改一次就可以满足新的需求。你就不用在使用了Trace的的每个类中进行修改了。也就是说,只用简单地重定义getTrace():

代码清单7
public class TraceFactory {
      public static Trace getTrace() {
            try {
                  return new FileTrace();
            } catch ( java.io.IOException ex ) {
                  Trace t = new SystemTrace();
                  t.error( "could not instantiate FileTrace: " + ex.getMessage() );
                  return t;
            }
      }
}

当不能确定一个类的什么具体实现要被实例化时,Factory method会很有用。你可以将那些细节留给Factory method。

在上面的例子中,你的程序不知道要创建FileTrace还是SystemTrace。因而,你可以只是用Trace来处理对象,对具体实现的实例化则留给Factory method。

上一篇 例程实作 下一篇 芥子须弥

TAG

Smile Big Smile Surprise Stick out tongue Wink Sad Tongue Tied Indifferent Crying Embarrassed Cool Angry Angel Devil [8-|] [:#] [:-*] [:^)] [<:o)] [|-)] Yes Beer Left Hug Music Star Time Snail Pizza Automobile Umbrella Computer Storm [mo] [8o|] [^o)] [+o(] [*-)] [8-)] Coffee No Drinks [Z] Right Hug Cake Broken Heart Gift Wilted Flower Movie Dog Idea Sleep Email Travel Paradise
呢称:

加粗 斜体 下划线 链接 图片 代码 邮件地址 引用 列表

最多只能输入100个字符

Tags

SQL 数据库 asp.net C# XML 控件 .NET教程 程序 事件 数据 安全 代码 Server 客户端 验证 数据库专栏 接口 文件 Oracle DataSet 函数 DataGrid 问题 .net return C#语言 JavaScript 服务 IIS 对象 语句 windows 继承 时间 web.config 设计 开发 参数 变量 解决 字符 ADO.net 环境 VB.Net语言 web 异常 工具 服务器 计算 实例 OLEDB Application VB Word WebService insert asp net 安装 记录

精华推荐

更多

精品下载

更多