代理模式——动态代理

 java语言通过java.lang.reflect苦,提供了三个类直接支持代理模式:Proxy,InvocoationHandler,Method三个类。

Prxoy能在运行时间创建代理对象,当系统有一个代理对象后,对源对象的方法调用会首先被分派给一个调用处理器(InvocationHandler接口),InvocationHandler接口中有一个invoke()方法,程序可以在调用处理器的invoke()方法中截获这个调用,进行额外的操作。

  1. public interface SaleComputer {
  2.     public void sale(String type);
  3. }

 

  1. public class ComputerMaker implements SaleComputer {
  2.     public void sale(String type) {
  3.         System.out.println("卖出了一台"+type+"电脑");
  4.     }
  5. }

 

  1. public class ComputerProxy {
  2.     public static SaleComputer getComputerMaker(){
  3.         ProxyFunction pf=new ProxyFunction();
  4.         return (SaleComputer)Proxy.newProxyInstance(ComputerMaker.class.getClassLoader(), ComputerMaker.class.getInterfaces(), pf);
  5.     }
  6. }

 

  1. public class ProxyFunction implements InvocationHandler {
  2.     private ComputerMaker cm;
  3.     
  4.     public void youHui(){
  5.         System.out.println("我给你一些优惠。。。");
  6.     }
  7.     
  8.     public void giveMouse(){
  9.         System.out.println("我还要送你一个鼠标。。。 ");
  10.     }
  11.     public Object invoke(Object arg0, Method arg1, Object[] arg2)
  12.             throws Throwable {
  13.         String type=(String)arg2[0];
  14.         if(type.equals("联想")||type.equals("三星")){
  15.             if(cm==null){
  16.                 cm=new ComputerMaker();
  17.                 youHui();
  18.                 giveMouse();
  19.                 arg1.invoke(cm, type);
  20.             }
  21.         }else{
  22.             System.out.println("我没有你要的这个牌子的电脑。。。。");
  23.         }
  24.         return null;
  25.     }
  26. }

 

  1. public class Test {
  2.     
  3.     public static void main(String[] args) {
  4.         SaleComputer sc=ComputerProxy.getComputerMaker();
  5.         //sc.sale("联想");
  6.         //sc.sale("三星");
  7.         sc.sale("Dell");
  8.     }
  9. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值