假設我們建立一個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"); } }