#format java /** * ProxyPattern example * proxy for heavy Printer instance */ interface Printable { public abstract void setPrinterName(String name); public abstract String getPrinterName(); public abstract void print(String string); } class Printer implements Printable { private String name; public Printer() { heavyJob("creating Printer instance..."); } public Printer(String name) { this.name = name; heavyJob("creating Printer instance ("+name+")..."); } public void setPrinterName(String name) { this.name = name; } public String getPrinterName() { return name; } public void print(String string) { System.out.println("=== "+name+" ==="); System.out.println(string); } private void heavyJob(String msg) { System.out.print(msg); for(int i=0; i < 5; i++) { try { Thread.sleep(1000); } catch(InterruptedException e) { } System.out.println("."); } System.out.println("...finished."); } } class PrinterProxy implements Printable { private String name; private Printer real; public PrinterProxy() { } public PrinterProxy(String name) { this.name = name; } public synchronized void setPrinterName(String name) { if(real != null) { real.setPrinterName(name); } this.name = name; } public String getPrinterName() { return name; } public void print(String string) { realize(); real.print(string); } private synchronized void realize() { if(real == null) { real = new Printer(name); } } } public class ProxyPrinter { public static void main(String[] args) { Printable p = new PrinterProxy("Alice"); System.out.println("name is "+p.getPrinterName()); p.setPrinterName("Bob"); System.out.println("name is "+p.getPrinterName()); p.print("Hello, world"); } }