最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java Q&A: 使用Factory Method模式(转)
时间:2022-07-02 18:03:37 编辑:袖梨 来源:一聚教程网
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 ) {
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 ) {
相关文章
- 时间旅者重生曙光公寓武器怎么获得 全部武器位置及收集攻略 09-19
- 地狱即我们研究物品有什么技能 研究物品技能图鉴 09-19
- 时间旅者重生曙光公寓全部猫位置攻略 全部猫咪在哪 09-19
- 地狱即我们研究道具怎么获取 道具获取方式及使用方法一览 09-19
- 时间旅者重生曙光公寓boss打法攻略 公寓boss怎么打 09-19
- 地狱即我们探索物品怎么收集 道具收集获取方式及使用合集 09-19