1 /**
   2  * ProxyPattern example
   3  * proxy for heavy Printer instance
   4  */
   5 
   6 interface Printable {
   7     public abstract void setPrinterName(String name);
   8     public abstract String getPrinterName();
   9     public abstract void print(String string);
  10 }
  11 
  12 class Printer implements Printable {
  13     private String name;
  14     public Printer() {
  15         heavyJob("creating Printer instance...");
  16     }
  17     public Printer(String name) {
  18         this.name = name;
  19         heavyJob("creating Printer instance ("+name+")...");
  20     }
  21     public void setPrinterName(String name) {
  22         this.name = name;
  23     }
  24     public String getPrinterName() {
  25         return name;
  26     }
  27     public void print(String string) {
  28         System.out.println("=== "+name+" ===");
  29         System.out.println(string);
  30     }
  31     private void heavyJob(String msg) {
  32         System.out.print(msg);
  33         for(int i=0; i < 5; i++) {
  34             try {
  35                 Thread.sleep(1000);
  36             } catch(InterruptedException e) {
  37             }
  38             System.out.println(".");
  39         }
  40         System.out.println("...finished.");
  41     }
  42 }
  43 
  44 class PrinterProxy implements Printable {
  45     private String name;
  46     private Printer real;
  47     public PrinterProxy() {
  48     }
  49     public PrinterProxy(String name) {
  50         this.name = name;
  51     }
  52     public synchronized void setPrinterName(String name) {
  53         if(real != null) {
  54             real.setPrinterName(name);
  55         }
  56         this.name = name;
  57     }
  58     public String getPrinterName() {
  59         return name;
  60     }
  61     public void print(String string) {
  62         realize();
  63         real.print(string);
  64     }
  65     private synchronized void realize() {
  66         if(real == null) {
  67             real = new Printer(name);
  68         }
  69     }
  70 }
  71 
  72 public class ProxyPrinter {
  73     public static void main(String[] args) {
  74         Printable p = new PrinterProxy("Alice");
  75         System.out.println("name is "+p.getPrinterName());
  76         p.setPrinterName("Bob");
  77         System.out.println("name is "+p.getPrinterName());
  78         p.print("Hello, world");
  79     }
  80 }
web biohackers.net