代理模式【PROXY PATTERN】

public interface Printable {
    public abstract void setPrinterName(String name);   
    public abstract String getPrinterName();            
    public abstract void print(String string);          
}

 public class Printer implements Printable {
    private String name;
    public Printer() {
        heavyJob("Printer()");
    }
    public Printer(String name) {                   // 僐儞僗僩儔僋僞
        this.name = name;
        heavyJob("Printer(" + 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.print(".");
        }
        System.out.println("");
    }
}

  
  public 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 Main {
     public static void main(String[] args) {
         Printable p = new PrinterProxy("Alice");
         System.out.println( p.getPrinterName() );
         p.setPrinterName("Bob");
         System.out.println( p.getPrinterName());
         p.print("Hello, world.");
     }
 }

你可能感兴趣的:(java,thread)