|
代理模式:為其他對象提供一種代理以控制對這個(gè)對象的訪問.說白了就是,在一些情況下客戶不想或不能直接引一個(gè)對象,而代理對象可以在客戶和目標(biāo)對象之間起到中介作用.去掉客戶不能看到的內(nèi)容和服務(wù)或都增添客戶需要的額外服務(wù). 給大家舉個(gè)比較簡單的例子: 假如你買臺IBM的筆記本,IBM產(chǎn)家是不提供鼠標(biāo)的.但是我們?nèi)绻麖拇砩痰氖掷镔I就有鼠標(biāo)和送. 很簡單的例子,寫幾個(gè)類來實(shí)現(xiàn)一下吧. 首先設(shè)計(jì)一個(gè)購買的接口代碼如下:(ComputerInterface.java) package test.lyx; publicinterface ComputerInterface { publicvoid buy(); } 建一個(gè)電腦類實(shí)現(xiàn)購買的接口代碼如下:(Computer.java) package test.lyx; publicclass Computer implements ComputerInterface{ private String pcName="IBMT60"; privateintpcPrice=17800; public String getPcName() { returnpcName; } publicvoid setPcName(String pcName) { this.pcName = pcName; } publicint getPcPrice() { returnpcPrice; } publicvoid setPcPrice(int pcPrice) { this.pcPrice = pcPrice; } publicvoid buy() { System.out.print("獲得筆記本電腦:"+pcName+"一臺"); } } 再建設(shè)一個(gè)代理商的類:用來完成買電腦和贈送鼠標(biāo):(ComputerProxy.java) package test.lyx; publicclass ComputerProxy { private ComputerInterface pci; public ComputerInterface getPci() { returnpci; } publicvoid setPci(ComputerInterface pci) { this.pci = pci; } publicvoid buy(){ pci.buy(); System.out.println("贈送鼠標(biāo)一個(gè)"); } } 建一個(gè)主函數(shù)測試一下吧:(TestDemo.java) package test.lyx; publicclass TestDemo { publicstaticvoid main(String[] args) { ComputerProxy c1=new ComputerProxy(); c1.setPci(new Computer()); c1.buy(); } } 運(yùn)行結(jié)果如下: 獲得筆記本電腦:IBMT60一臺獲得鼠標(biāo)一個(gè) 以上就是代理功能的實(shí)現(xiàn),由代理商銷售筆記本,并贈送鼠標(biāo).但是這樣的程序只適合是銷售IBM筆記本.那么如果要是其它品牌呢.所以我們來更改一個(gè)代理類.來實(shí)現(xiàn)動態(tài)的代理. 建立一個(gè)類代碼如下:(ComputerProxy2.java) package test.lyx; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; publicclass ComputerProxy2 implements InvocationHandler{ private Object delegate; //描述是誰的代理,也就是與那個(gè)類有關(guān)系 public Object bind(Object delegate){ this.delegate=delegate; return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(),this); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("贈送鼠標(biāo)一個(gè)!"); Object result=method.invoke(delegate, args); return result; } } 然后在主函數(shù)中加上: ComputerProxy2 c2=new ComputerProxy2(); ComputerInterface ci2=(ComputerInterface)c2.bind(new Computer()); ci2.buy(); 就可以實(shí)現(xiàn)動態(tài)代理了. |
|
|