原理:
时序图:
代码清单:
Printable
public interface Printable { void setPrinterName(String name); String getPrinterName(); void print(String string);}
PrintProxy
public class PrinterProxy implements Printable{ private String name; private Printer real; public PrinterProxy(String name){ this.name = name; } @Override public synchronized void setPrinterName(String name) { if(real != null){ real.setPrinterName(name); } this.name = name; } @Override public String getPrinterName() { return name; } @Override public void print(String string) { realize(); real.print(string); } private synchronized void realize(){ if(real == null){ real = new Printer(name); } }}
Printer
public class Printer implements Printable{ private String name; public Printer(){ heavyJob("正在生成printer 实例"); } public Printer(String name){ this.name = name; heavyJob("正在生成printer 实例"+name); } @Override public void setPrinterName(String name) { this.name = name; } @Override public String getPrinterName() { return name; } @Override public void print(String string) { System.out.println("===="+name+"===="); System.out.println(string); } public void heavyJob(String msg){ System.out.println(msg); for(int i=0;i<5;i++){ try{ Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } System.out.print("."); } System.out.println("结束"); }}
Main
public class Main { public static void main(String[] args){ Printable p = new PrinterProxy("A1"); System.out.println("现在的名字:"+p.getPrinterName()); p.setPrinterName("B1"); System.out.println("现在的名字:"+p.getPrinterName()); p.print("你好"); }}