proxy 的原理

设计模式中proxy模式可以在jdk中的proxy得到体现。
它也是spring的核心思想。

首先我定义个ActionPrettyWomanInterface 接口。
public interface ActionPrettyWomanInterface {
void action();
}


针对于这个接口,我们可以有多个实现。
一个是帮助美女的实现。
public class HelpPrettyWoman implements ActionPrettyWomanInterface{
public void action() {
System.out.println("我在帮美女补丝袜 .");
}
}

另一个是玩美女。
public class PlayPrettyWoman implements ActionPrettyWomanInterface{
public void action() {
System.out.println("我在玩美女.");
}
}


那么我们只是简单的玩,是不是太没情调了呢。
这时候我们就可以通过代理机制里的InvocationHandler加入一些情调。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class SexyInvocationHandler implements InvocationHandler{
private Object prettyWoman;
public SexyInvocationHandler(ActionPrettyWomanInterface prettyWoman){
this.prettyWoman=prettyWoman;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result=null;
try{
System.out.println(proxy.getClass().getSimpleName());
System.out.println("让美女穿上丝袜,剪开档.");
result =method.invoke(prettyWoman, args);
System.out.println("抽跟烟~~~.");
}catch(Exception e){
}
return result;
}

}



之后我们就可以大玩特玩了。
import java.lang.reflect.Proxy;
public class TestActionWithWoman {
public static void main(String[] args) {
ActionPrettyWomanInterface playWoman=new PlayPrettyWoman();
ActionPrettyWomanInterface helpWoman=new HelpPrettyWoman();
ActionPrettyWomanInterface fuckProxy=(ActionPrettyWomanInterface)Proxy.
newProxyInstance(playWoman.getClass().getClassLoader(), playWoman.getClass().getInterfaces(), new SexyInvocationHandler(playWoman));
fuckProxy.action();
ActionPrettyWomanInterface remedyProxy=(ActionPrettyWomanInterface)Proxy.
newProxyInstance(helpWoman.getClass().getClassLoader(), helpWoman.getClass().getInterfaces(), new SexyInvocationHandler(helpWoman));
remedyProxy.action();
System.out.println("fuckProxy classname:"+fuckProxy.getClass().getName());
}
}


控制台输出:
[quote]$Proxy0
让美女穿上丝袜,剪开档.
我在玩美女.
抽跟烟~~~.
$Proxy0
让美女穿上丝袜,剪开档.
我在帮美女补丝袜 .
抽跟烟~~~.
fuckProxy classname:$Proxy0[/quote]

从中我们可以知道,当我们用代理机制创建关于接口或者类的对象时候,
它的对象实现是jdk产生的动态代理对象Proxy0。

当我们要调用玩美女或者帮助美女方法时候, 它的实际顺序是先调用InvocationHandler里的invoke, 然后invoke会通过反射调用玩美女或者帮助美女方法。


得出结论:如果我们不实现InvocationHandler的invoke方法,那么我们实际中的方法讲不会被调用到。所以这个类必须重写。

然后另外我们可以得知,创建对象除了new以后,还可以通过代理实现。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值