JDK代理(依赖接口)
public interface LetRoom {
void zf();
}
public class FangDong01 implements LetRoom {
@Override
public void zf() {
System.out.println("出租房屋01");
}
}
public class FangDong02 implements LetRoom {
@Override
public void zf() {
System.out.println("出租房屋02");
}
}
/**
* 动态产生代理对象
*/
public class MyInv implements InvocationHandler {
private LetRoom letRoom;
public MyInv(LetRoom letRoom) {
this.letRoom = letRoom;
}
public Object getProxy(){
return Proxy.newProxyInstance(MyInv.class.getClassLoader(),new Class[]{LetRoom.class},this);
}
//这个方法就是给用户的租房方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("--收取介绍费500元--");
//调用房东的租房方法
Object invoke = method.invoke(letRoom, args);
System.out.println("--收取差价800元--");
return invoke;
}
}
public class Test01 {
public static void main(String[] args) {
MyInv myInv = new MyInv(new FangDong02());
//返回的是动态产生的代理(中介)对象
LetRoom proxy = (LetRoom) myInv.getProxy();
//调用中介的租房方法
proxy.zf();
}
}
CGLIB代理
public class FangDong03 {
public void zf(){
System.out.println("出租房屋03");
}
}
public class MyIntp implements MethodInterceptor {
public Object getProxy(){
Enhancer en=new Enhancer();
//设置代理对象的父类
en.setSuperclass(FangDong03.class);
en.setCallback(this);
Object o = en.create();
return o;
}
/**
* @param method:被代理对象中的方法
* @param methodProxy:代理对象中的方法
*/
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("--收取介绍费500元--");
Object o1 = methodProxy.invokeSuper(o, objects);
System.out.println("--收取差价800元--");
return o1;
}
}
public class Test02 {
public static void main(String[] args) {
MyIntp myIntp=new MyIntp();
FangDong03 proxy = (FangDong01) myIntp.getProxy();
proxy.zf();
}
}