假设我们建立一个JAVA程序的集成开发环境(Integrated Development Environment),这个环境包括三个功能:编译、运行、生成JavaDoc文档。在新建和编辑Java程序时,最为常用的是编译和运行。至于生成JavaDoc文档对于每一个Java程序不是必需的。因此,在Java开发环境启动时,不要创建和装载实现集成开发环境全部功能的所有对象,仅创建那些在编辑、编译、运行时用到的对象,保留提供生成JavaDoc文档的对象,这是一个好的设计思想。这种对象创建策略能够高效地利用内存空间并且加快了集成开发环境的启动速度。
public abstract class IDEOperation {
private Compiler cmp;
private Runtime rtime;
public void compile(String javaFile) {
cmp.compile(javaFile);
}
public void run(String classFile) {
rtime.run (classFile);
}
//to be delayed until needed.
public abstract void generateDocs(String javaFile);
public IDEOperation() {
cmp = new Compiler();
rtime = new Runtime();
}
}
public class RealProcessor extends IDEOperation {
JavaDoc jdoc;
public RealProcessor() {
super();
jdoc = new JavaDoc();
}
public void generateDocs(String javaFile) {
jdoc.generateDocs(javaFile);
}
}
public class ProxyProcessor extends IDEOperation {
private RealProcessor realProcessor;
public void generateDocs(String javaFile) {
/*
In order to generate javadocs
the proxy loads the actual object and
invokes its methods.
*/
if (realProcessor == null) {
realProcessor = new RealProcessor();
}
realProcessor.generateDocs(javaFile);
}
}
public class Client {
public static void main(String[] args) {
/*
At this point objects required for
the compile and run operations are
created, but not the objects that provide the
generate Javadoc functionality.
*/
IDEOperation IDE = new ProxyProcessor();
IDE.compile("test.java");
IDE.run("test.class");
/*
The Javadoc functionality is accessed
For the first time and hence the
Object offering the Javadoc generation
Functionality is loaded at this point.
*/
IDE.generateDocs("test.java");
}
}