简单阐述对动态代理的理解
动态代理是通过反射机制,在程序的运行过程中,动态的为目标对象生成代理对象的一种代理方式,代理模式也是设计模式的一种;
动态代理有两种方式,JDK实现动态代理和cglib实现动态代理,其中cglib实现了目标类(Target)不需要实现接口也一样可以实现动态代理;
代理可以形象的理解成比如去商店消费,其实商店就是厂商的代理,租房子,中介就是房东的代理;
JDK实现动态代理:
接口类:
package com.wuman.service;
//表示功能的,厂家商家都要完成的功能
public interface UsbSell {
/**
*
* @param amount 表示一次购买的数量,暂时不用
* @return 返回值表示一个U盘的价格
*/
float sell(int amount);
}
厂商类(目标类):
package com.wuman.factory;
import com.wuman.service.UsbSell;
//目标类
public class UsbFactory implements UsbSell {
public float sell(int amount) {
//目标方法
System.out.println("目标类中,执行sell目标方法");
return 85.0f;
}
}
实现InvocationHandler接口类:
package com.wuman.handler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
//必须实现InvocationHandler接口,靠它完成JDK动态代理(1.调用目标方法 2.功能增强)
public class MySellHandler implements InvocationHandler {
//动态代理:目标对象是活动的,不是固定的,需要传入进来
//传入是谁,就给谁创建代理
public MySellHandler(Object target) {
//给目标对象赋值
this.target = target;
}
private Object target = null;
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//向厂家发送订单,告诉厂家,我卖了U盘,厂家发货
//float price = usbFactory.sell(amount);//厂家的价格
Object res = null;
res = method.invoke(target, args);//执行目标方法
//商家 需要加价,也就是代理要增加价格
//price = price + 25;//增强功能,代理类在完成目标类方法调用后,增强了功能
if (res != null) {
Float price = (Float) res;
price = price + 25;
res = price;
}
//在目标类的方法调用后,你做的其它功能,都是增强的意思
//增加的价格
return res;
}
}
测试类:
package com.wuman.main;
import com.wuman.factory.UsbFactory;
import com.wuman.handler.MySellHandler;
import com.wuman.service.UsbSell;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class ShopMain {
public static void main(String[] args) {
//创建代理对象
//1.创建目标对象
UsbSell usbFactory = new UsbFactory();
//2.创建InvocationHandler对象
InvocationHandler handler=new MySellHandler(usbFactory);
//3.创建代理对象
UsbSell proxy= (UsbSell) Proxy.newProxyInstance(usbFactory.getClass().getClassLoader(),usbFactory.getClass().getInterfaces(),handler);
//4.通过代理执行方法
float price = proxy.sell(1);
System.out.println("通过动态代理,调用方法得到的:"+price);
}
}
代理对象的创建可以在测试类,也可以在Handler类中;
JDK实现动态代理,InvocationHandler,invoke,proxy是必要的三步
在实现InvocationHandler的类中,需要声明一个Object的对象,及其构造方法,用于动态代理对于对象的动态创建。