动态代理demo
public interface Girl {
void date();
void watchMovie();
}
public class HotGirl implements Girl {
public HotGirl(){
System.out.println("从前有位火辣妹子,想找个帅哥出去玩," +
"但是很难找到符合自己的,所以就去找代理机构帮忙");
}
@Override
public void date() {
System.out.println("===========女生心想,nice ,终于有帅哥和我约会啦===========");
}
@Override
public void watchMovie() {
System.out.println("===========女生心想,nice ,终于有帅哥和我看电影啦===========");
}
public class WXProxy implements InvocationHandler {
private Girl girl;
public WXProxy(Girl girl){
System.out.println("代理机构接待了这位妹子,让妹子留一份生活信息");
this.girl = girl;
}
void proxyFront(){
System.out.println("代理机构会先看看这个男生的基本信息是否符合这位妹子," +
"做过调查后,觉得蛮匹配的让他开始约女生");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
proxyFront();
Object invoke = method.invoke(girl,args);
dateAfter();
return invoke;
}
void dateAfter(){
System.out.println("约会过后,代理机构去询问妹子,这个男生是否合适,有没有第二次约会意向之类的");
}
public Object getProxyInstance(){
System.out.println("代理机构就开始整理这位妹子的基础资料,并为她发布找帅哥出去玩的信息");
return Proxy.newProxyInstance(girl.getClass().getClassLoader(),girl.getClass().getInterfaces(),this );
}
}
public class HandsomeBoy {
public static void main(String[] args) {
HotGirl hotGirl = new HotGirl();
WXProxy wxProxy = new WXProxy(hotGirl);
Girl girl = (Girl)wxProxy.getProxyInstance();
System.out.println("这个时候有位帅哥,看到了这位妹子的信息,觉得不错,就去找代理机构咨询");
girl.date();
System.out.println("============================================");
girl.watchMovie();
}
}
输出结果:
|