|
TOP
|
| [ 录入者:admin | 时间:2007-11-30 12:47:01
| 作者: | 来源:原创
| 浏览:15次 ] |
java开源文档大全致力于打造中国最大最全的开源文档,它提供了最全面最权威的开源资料,同时为大家提供一个交流的平台,如果您有好的想法,欢迎您投稿.
代理模式:为其他对象提供一种代理以控制对这个对象的访问.说白了就是,在一些情况下客户不想或不能直接引一个对象,而代理对象可以在客户和目标对象之间起到中介作用.去掉客户不能看到的内容和服务或都增添客户需要的额外服务. 给大家举个比较简单的例子: 假如你买台IBM的笔记本,IBM产家是不提供鼠标的.但是我们如果从代理商的手里买就有鼠标和送. 很简单的例子,写几个类来实现一下吧. 首先设计一个购买的接口代码如下:(ComputerInterface.java) package test.lyx; publicinterface ComputerInterface { publicvoid buy(); } 建一个电脑类实现购买的接口代码如下:(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+"一台"); } } 再建设一个代理商的类:用来完成买电脑和赠送鼠标:(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("赠送鼠标一个"); } } 建一个主函数测试一下吧:(TestDemo.java) package test.lyx; publicclass TestDemo { publicstaticvoid main(String[] args) { ComputerProxy c1=new ComputerProxy(); c1.setPci(new Computer()); c1.buy(); } } 运行结果如下: 获得笔记本电脑:IBMT60一台获得鼠标一个 以上就是代理功能的实现,由代理商销售笔记本,并赠送鼠标.但是这样的程序只适合是销售IBM笔记本.那么如果要是其它品牌呢.所以我们来更改一个代理类.来实现动态的代理. 建立一个类代码如下:(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; //描述是谁的代理,也就是与那个类有关系 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("赠送鼠标一个!"); Object result=method.invoke(delegate, args); return result; } } 然后在主函数中加上: ComputerProxy2 c2=new ComputerProxy2(); ComputerInterface ci2=(ComputerInterface)c2.bind(new Computer()); ci2.buy(); 就可以实现动态代理了. [b][/b]
java开源文档研究struts,webwork,spring,tomcat,jboss,lucense,nutch,JUnit,eclipse......,如果您有什么意见,欢迎评论和留言. |
|
|
|
|
|