java 动态代理

设计模式中又一个著名的模式代理模式,大多数人熟知的时静态代理,今天魔门研究一下动态代理,sun公司为我们提供了一个动态代理类Proxy和一个动态代理处理接口invocationHandler 

动态代理的优点:

1.代码比较灵活

2.不会产生过多的冗杂类

我们看一个例子吧:

/**
 * 接口类(日志管理)
 *
 */
public interface IlogManager {

public void log();
}


/**
 * 具体实现类
 *
 */
public class LogManager implements IlogManager {


public void log(){
System.out.println("log..................");
}
}


/**
 * 插入的功能类(切入类)
 *
 */
public class computateTime {


public long getNow(){
return System.currentTimeMillis();
}

}


/**
 *  处理类 
 *
 */
public class computateTimeHandler implements InvocationHandler {

private IlogManager logIntance;

private computateTime cTime;
/**
 * 重写构造
 */
public computateTimeHandler(IlogManager logIntance,computateTime cTime) {
super();
this.logIntance = logIntance;
this.cTime = cTime;
}

//下面这个方法是关键,三个参数分别代表 需要代理的类,需要执行方法,方法参数
@Override
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
long before = cTime.getNow();
method.invoke(logIntance, args);
long after = cTime.getNow();
System.out.print(after-before);
return null;//没有返回值便不返回
}

}


客户端

public class Client {
public static void main(String[] args) {
IlogManager lm = new LogManager();
computateTime cTime = new computateTime();
InvocationHandler h = new computateTimeHandler(lm,cTime);

 //loader   the class loader to define the proxy class 

//inerfaces    the list of interfaces for the proxy class  to implement
//h   the invocation handler to dispatch method invocations to

//生成代理类    
IlogManager ProxyLm = (IlogManager) Proxy.newProxyInstance(lm.getClass().getClassLoader(),lm.getClass().getInterfaces() , h);

//代理执行方法
ProxyLm.log();
}
}


动态代理在框架方面应用最多,尤其是springmvc的aop(面向切面编程),使代码更加灵活


下一篇文章将讲解动态代理类

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值