动态代理

抽象角色

package com.dynamicProxy;

public interface Rent {
public void rent();
}

真实角色

package com.dynamicProxy;

public class Landlord implements Rent {
public void rent() {
System.out.println("房东出租房子");
}
}

代理角色(代理类)

package com.dynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
* @author AustinSpark
*
*/
public class ProxyInvocationalHandler implements InvocationHandler {

private Object target;

public void setTarget(Object target) {
this.target = target;
}

/**
* 生产代理类
* **/
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target
.getClass().getInterfaces(), this);
}

/**
* proxy 代理类 method 真实对象
* method 代理类的调用处理程序的方法对象
* **/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = method.invoke(target, args);
return result;
}

}

用户角色

package com.dynamicProxy;

public class Client {

public static void main(String[] args) {
Landlord ll = new Landlord();
ProxyInvocationalHandler pih = new ProxyInvocationalHandler();
pih.setTarget(ll);
Rent rent = (Rent) pih.getProxy();
rent.rent();
}

}

将   真实角色   给代理类

使用Java动态代理机制的好处:

1、减少编程的工作量:假如需要实现多种代理处理逻辑,只要写多个代理处理器就可以了,无需每种方式都写一个代理类。

2、系统扩展性和维护性增强,程序修改起来也方便多了(一般只要改代理处理器类就行了)。

原文地址:https://www.cnblogs.com/austinspark-jessylu/p/5679778.html