本文共 2072 字,大约阅读时间需要 6 分钟。
代理是通知目标对象后创建的对象。从客户端的角度看,代理对象和目标对象是一样的。
public interface Rent { void Renthouse();}
public class Host implements Rent { @Override public void Renthouse() { System.out.println("房东有一套房子出租!!!"); }}
public class Proxy implements Rent { private Host host; public Proxy(Host host) { this.host = host; } @Override public void Renthouse() { host.Renthouse(); Money(); seeHose(); hetong(); } public void Money() { System.out.println("中介-收取一定的报酬会"); } public void seeHose() { System.out.println("中介-带我看房子。"); } public void hetong() { System.out.println("满意的话,签合同!"); }}
public class client { public static void main(String[] args) { Host host = new Host(); Proxy proxy = new Proxy(host); proxy.Renthouse(); }}
动态代理分为三大类:基于接口(JDK动态代理)、基于类(CGLIB动态代理)、Java字节码实现(Javassist)。
public interface Rent { void Rent();}
public class Host implements Rent { @Override public void Rent() { System.out.println("房东有一整套房子出租!!!"); }}
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 ); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(rent, args); }}
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.Rent(); }}
通过以上内容,可以看出动态代理在实际应用中的重要性和优势。
转载地址:http://venv.baihongyu.com/