代理的一个经典应用场景就是当一个实体类不能直接访问目标类中的方法,而此时就需要一个中间代理类帮助该实体类访问该目标类的方法(例如魔法),实现控制访问、功能增强。
在JDK的代理模式中分为静态代理和动态代理两种模式,对于静态代理而言对于每一个中间代理类都需要我们手动创建,其中不乏业务逻辑相同的代码,造成代码冗余;而且每次当代理类实现接口的抽象方法发生变化时,目标类和代理类都需要手动修改源码,不利于代码维护。而动态代理便对该缺陷进行了优化,将代理类对象的创建交由JDK的反射机制处理,重复的业务逻辑代码可以被全部封装到一个实现了InvocationHandler接口的代理类中,通过重写invoke方法在其中进行功能增强的代码实现,最后通过Proxy获取目标类的代理对象后就可以直接调用目标类的方法。
但JDK的动态代理机制需要目标类一定要实现一个接口,而Cglib则只需要目标类能够被继承即可
以下是JDK动态代理实现的示例代码
package com.test;
import com.test.proxy.MyInvocation;
import com.test.usbsell.Factory;
import com.test.usbsell.UsbSell;
import java.lang.reflect.Proxy;
public class Shop {
public static void main(String[] args) {
UsbSell usbSell = new Factory();
MyInvocation myInvocation = new MyInvocation(usbSell);
UsbSell res = (UsbSell) Proxy.newProxyInstance(usbSell.getClass().getClassLoader(), usbSell.getClass().getInterfaces(), myInvocation);
System.out.println(res.sell("12345"));
}
}
package com.test.proxy;
import com.test.usbsell.UsbSell;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocation implements InvocationHandler {
private UsbSell target;
public MyInvocation(UsbSell usbSell) {
this.target = usbSell;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object res = method.invoke(target, args);
float price = 10;
if (res != null) {
price += (Float)res;
System.out.println("give you a coupon");
}
return price;
}
}
package com.test.usbsell;
public class Factory implements UsbSell {
@Override
public float sell(String info) {
System.out.println(info);
return 100.5f;
}
}
package com.test.usbsell;
public interface UsbSell {
float sell(String info);
}