特点:字节码随用随创建,随用随加载。(不同于装饰模式)
作用:不修改源码的基础上对方法增强
分类:
基于接口的动态代理:
public static void main(String[] args)
{
final Producer producer = new Producer();
IProducer iProducer = (IProducer) Proxy.newProxyInstance(Producer.class.getClassLoader(), Producer.class.getInterfaces(), new InvocationHandler()
{
/**
* 作用:执行被代理对象的任何接口方法都会经过该方法
* @param proxy 代理对象的引用
* @param method 当前执行的方法
* @param args 当前执行方法所需要的参数
* @return 和被代理对象方法有相同的返回值
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
Object returnValue = null;
// 1.获取方法执行的参数
Float money = (Float) args[0];
// 2.判断当前方法是不是销售
if ("saleProduct".equals(method.getName()))
{
System.out.println("代理商获取0.2的利润");
returnValue = method.invoke(producer, money * 0.8f);
}
return returnValue;
}
});
iProducer.saleProduct(1000f);
}
public static void main(String[] args)
{
final Producer producer = new Producer();
Producer proxyProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor()
{
/**
* 执行被代理对象方法都会经过该方法
* @param proxy
* @param method
* @param args
* 以上三个参数和基于接口实现动态代理一样
* @param methodProxy 当前执行方法的代理对象
* @return
* @throws Throwable
*/
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable
{
Object returnValue = null;
// 1.获取方法执行的参数
Float money = (Float) args[0];
// 2.判断当前方法是不是销售
if ("saleProduct".equals(method.getName()))
{
System.out.println("代理商获取0.2的利润");
returnValue = method.invoke(producer, money * 0.8f);
}
return returnValue;
}
});
proxyProducer.saleProduct(1000f);
}
原文:https://www.cnblogs.com/jinchengll/p/11783337.html