一,静态代理(房产中介)
/** * 抽象角色,真实角色和代理角色都要实现的接口 * @author marcopan */ public interface IAbstractSubject { // 代理对象和真实角色共有的方法,租房() public void rentHouse(); } /** * 真实角色--房东 * @author marcopan * */ public class RealSubject implements IAbstractSubject { @Override public void rentHouse() { System.out.println("rentHouse from RealSubject"); } } package proxy.staticProxy; /** * 代理角色,中介,含有真实角色的引用 * @author marcopan * 代理角色做两件事: * 1. 关联真实角色对象 * 2. 调用真实对象方法 */ public class StaticProxySubject implements IAbstractSubject { // 含有真实角色的引用 private RealSubject realSubject = null; public StaticProxySubject(RealSubject subject) { this.realSubject = subject; } @Override public void rentHouse() { realSubject.rentHouse(); } } public class Client { public static void main(String[] args) { IAbstractSubject proxySubject = new StaticProxySubject(new RealSubject()); proxySubject.rentHouse(); } }
二,动态代理
/**
* 抽象角色,真实角色和代理角色都要实现的接口
* @author marcopan
*/
public interface IAbstractSubject {
public void requestHouse1();
public void requestHouse2();
}
/**
* 真实角色--房东
* @author marcopan
*/
public class RealSubject implements IAbstractSubject {
@Override
public void requestHouse1() {
System.out.println("requestHouse1 from RealSubject");
}
@Override
public void requestHouse2() {
System.out.println("requestHouse2 from RealSubject");
}
}
public class DynamicProxySubject implements InvocationHandler {
private RealSubject realSubject = null;
public DynamicProxySubject(RealSubject realObject) {
this.realSubject = realObject;
}
@Override
/**
* proxy:指代理对象,com.sun.proxy.$Proxy0
* method:指代的是我们所要调用真实对象的某个方法的Method对象
* args:指代的是调用真实对象某个方法时接受的参数
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
method.invoke(realSubject, args);
return null;
}
}
public class Client {
public static void main(String[] args) {
RealSubject iSubject = new RealSubject();
InvocationHandler handler = new DynamicProxySubject(iSubject);
/**
* Proxy这个类的作用就是用来动态创建一个代理对象的类
* Proxy.newProxyInstance返回的是一个代理对象:com.sun.proxy.$Proxy0
* 根据handler.getClass().getClassLoader()和iSubject.getClass().
getInterfaces()构造Class对象,Class对象的构造函数入参是handler
*/
IAbstractSubject proxySubject = (IAbstractSubject) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
iSubject.getClass().getInterfaces(),
handler);
System.out.println(proxySubject.getClass().getName());
//调用的是super.h.invoke(this, , ),DynamicProxySubject的invoke方法
proxySubject.requestHouse1();
proxySubject.requestHouse2();
}
}
原文:http://www.cnblogs.com/panning/p/7747754.html