关于静态代理和动态代理代码解释

#

静态代理

####代理对象和被代理的对象其实都是为实现同一目标接口动作而被创建,只不过代理对象只是间接使用被代理对象的实现方法而去实现这个动作.

同一目标接口: //出租房子 ------------

public interface Rent { void rent(); } 

 

被代理的对象://真实业主 ------------ 

public class Host implements Rent {
 @Override
 public void rent() { 
System.out.println("业主要出租房子"); 
} }

 

代理对象://中介 ------------

public class Proxy implements Rent { 

private Host host;
 public Proxy() { } 

public Proxy(Host host) { this.host = host; } 
@Override 

public void rent() { 

//实现业主租房的想法 
host.rent(); }
} 

 

客户端: ------------

public static void main(String[] args) { 
Host host = new Host(); 
Proxy proxy = new Proxy(host);
 proxy.rent(); }

 

动态代理模式: ------------ 动态代理就是省去了代理对象这个实体,利用反射,在需要代理对象时自动创建

同一目标接口://租房 ------------

 public interface Rent { void rent(); } 

 

被代理对象://业主租房 ------------ 

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

 

动态代理对象://生成代理的中介 ------------

public class ProxyInvocationHandler implements InvocationHandler { 

private Object target; 

public void setRent(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 { 
Object invoke = method.invoke(target, args); return invoke; }

} 

 

客户端: ------------ 

public static void main(String[] args) {
 Host host = new Host(); 
ProxyInvocationHandler pih = new ProxyInvocationHandler();
 pih.setRent(host);
 Rent proxy = (Rent) pih.getProxy(); 
proxy.rent(); }

 

posted @ 2021-07-20 21:30  蔚然长空  阅读(57)  评论(0编辑  收藏  举报