动态代理的原理
使用一个代理将对象包装起来,然后用该代理对象取代原始对象。任何对原始对象的调用都要通过代理。代理对象决定是否以及何时将方法调用转到原始对象上。
动态代理使用场合:
调试
远程方法调用
动态代理相比于静态代理的优点:
抽象角色中(接口)声明的所有方法都被转移到调用处理器一个集中的方法中处理,这样,我们可以更加灵活和统一的处理众多的方法。
静态代理和动态代理案例
静态代理
/*
* 静态代理案例
*
* 特点 : 代理类和被代理类在编译期间就确定了下来
* */
// 衣物工厂
interface ClothFactory{
// 生产衣物
void produceCloth();
}
// 代理类
class ProxyClothFactory implements ClothFactory{
private ClothFactory clothFactory;
public ProxyClothFactory(ClothFactory clothFactory){
this.clothFactory=clothFactory;
}
@Override
public void produceCloth()
{
System.out.println("代理工厂正在准备");
clothFactory.produceCloth();
System.out.println("代理工厂准备收尾");
}
}
// 被代理对象 耐克品牌
class NikeClothFactory implements ClothFactory{
@Override
public void produceCloth()
{
System.out.println("耐克工厂生产服装");
}
}
public class StaticProxyTest
{
public static void main(String[] args)
{
// 创建被代理类对象
NikeClothFactory nike=new NikeClothFactory();
// 创建代理类对象
ClothFactory proxyClothFactory=new ProxyClothFactory(nike);
proxyClothFactory.produceCloth();
}
}
动态代理
/*
* 动态代理
* 特点 :代理对象在运行时才确定
* */
// 人类
interface Human{
// 信仰
String getBelief();
// 吃
void eat(String food);
}
class Superman implements Human{
@Override
public String getBelief()
{
return "超人信仰佛教";
}
@Override
public void eat(String food)
{
System.out.println("超人爱吃:" + food);
}
}
class ProxyFactory{
// 调用此方法,返回一个代理类对象
public static Object getProxyInstance(Object obj){
MyInvocationHandler myInvocationHandler=new MyInvocationHandler();
myInvocationHandler.bind(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),myInvocationHandler);
}
}
class MyInvocationHandler implements InvocationHandler{
// 创建被代理类
private Object obj;
public void bind(Object obj){
this.obj =obj;
}
// 当我们通过代理类的对象,调用方法a时,就会自动的调用如下invoke方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
// 将被代理类要执行的方法a 的功能就声明在invoke方法中
Object invoke = method.invoke(obj, args);
// 上述方法的返回值就是invoke方法的返回值
return invoke;
}
}
public class ProxyTest
{
public static void main(String[] args)
{
Superman superman=new Superman();
Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superman);
System.out.println(proxyInstance.getBelief());
proxyInstance.eat("菠菜");
}
}