1、代码实现
1.1、代理接口
public interface Rent {
public void rent();
}
1.2、真实角色
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
1.3、动态代理
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Rent rent;
public void setRent(Rent rent){
this.rent = rent;
}
//生成代理对象
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
@Override
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
//动态代理的本质就是反射
Object result = method.invoke(rent, args);
fare();
return result;
}
public void seeHouse(){
System.out.println("看房子");
}
public void fare(){
System.out.println("收中介费");
}
}
1.4、使用动态代理
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setRent(host);
//生成代理对象
Rent proxy = (Rent) pih.getProxy();//这个proxy就是动态生成的
proxy.rent();
}
}
2、通用代码实现
2.1、代理接口
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
2.2、真实角色
public class UserServiceImp implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("增更新了一个用户");
}
@Override
public void select() {
System.out.println("查找了一个用户");
}
}
2.3、动态代理
//使用这个类生成代理对象
public class ProxyInvocationHandler 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);
}
@Override
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
//动态代理的本质就是反射
Object result = method.invoke(target, args);
return result;
}
public void log(String msg){
System.out.println("[Debug]: 执行了"+msg+"方法");
}
}
2.4、使用动态代理
public class Client {
public static void main(String[] args) {
//真是角色
UserServiceImp userService = new UserServiceImp();
//代理角色 不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);//设置要代理的对象
//动态生成代理类
//错误代码:UserServiceImp proxy = (UserServiceImp) pih.getProxy();
UserService proxy = (UserService) pih.getProxy();
proxy.add();
proxy.delete();
proxy.update();
proxy.select();
}
}