设计模式中的代理模式

     本人在学习设计模式时总结的一点经验写出与大家一同分享:

     其实代理模式是分两总代理,一种是静态代理,另一种是动态代理。静态代理是先声明一个接口,然后用一个类实现这个接口。然后新建另一个类也实现这个接口,在这个类中声明一个属性引用前一个类。在实在方法时做你想做的事,然后在运行前一个类实现的方法。

package org.jms.beans.test;

public interface ComputerInterface {
   void computerFunction();
}

package org.jms.beans.test;

public class PrintFunction implements ComputerInterface {

 public void computerFunction() {
  // TODO Auto-generated method stub
        System.out.println("计算机有打印功能。");
 }

}

package org.jms.beans.test;

public class ProxyComputerFunction implements ComputerInterface {
 private ComputerInterface printfunction  ;
 
 public ComputerInterface getPrintfunction() {
  return printfunction;
 }

 public void setPrintfunction(ComputerInterface printfunction) {
  this.printfunction = printfunction;
 }

 public void computerFunction() {
  // TODO Auto-generated method stub
  System.out.println("先把打印机打开..");
  printfunction.computerFunction();
 }

}

建一个测试类

package org.jms.beans.test;

public class ProxyTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  ProxyComputerFunction proxyComputerFunction = new ProxyComputerFunction();
  proxyComputerFunction.setPrintfunction(new PrintFunction());
  proxyComputerFunction.computerFunction();
 }

}
动态代理则是实现 InvocationHandler 这个接口,在这个实现类中绑定一个对象。

package org.jms.beans.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DyProxy implements InvocationHandler {
    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 {
  // TODO Auto-generated method stub
  System.out.println("先把打印机打开...");
  return  method.invoke(delegate, args);
 }

}

测试一下

package org.jms.beans.test;

public class ProxyTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  DyProxy dyProxy = new DyProxy();
  ComputerInterface computer = (ComputerInterface) dyProxy.bind(new PrintFunction());
  computer.computerFunction() ;
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值