首页 > 其他 > 详细

代理模式及实现

时间:2018-08-07 21:53:58      阅读:191      评论:0      收藏:0      [点我收藏+]

技术分享图片 

代理对象和委托对象继承相同接口,并控制外部对委托对象的访问。

1. 静态代理: 代理对象在编译期确定。

接口(Human):

public interface Human{
    public void eatFood();
}

委托类(HumanImpl):

public class HumanImpl implements Human{
    public void eatFood(){
        System.out.print("真香!");
    }
}

代理类(HumanProxy):

public class HumanProxy implements Human{
    private Human human;

    public HumanProxy(Human human){
            this.human = human;
    }
    
    public void eatFood(){
        before();
        human.eatFood();
        after();
    }
}

 

2. 动态代理: 运行期生成代理对象

  在代理类和委托类之间生成中介类,该类实现 InvocationHandler 接口。对委托对象方法的调用会转到中介对象的invoke()方法中,method标识了调用哪一个方法,args代表方法参数。

  不需要实现代理的接口。

public class HumanDynamicProxy implements InvocationHandler{
    //委托对象
    private Human human;
    public HumanDynamicProxy(Human human){
        this.human = human;
    }
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(); Object result = method.invoke(human, args); after(); return result; } }

测试代码:

public static void main(String[] args){
    //委托对象
    Human realHuman = new HumanImpl();
    //中介
    InvocationHandler  handler = new HumanDynamicProxy(human);
    //动态代理
    Human proxy = (Human) Proxy.newProxyInstance(realHuman.getClass().getClassLoader(), realhuman.getClass().getInterfaces(), handler);
    //通过代理类,执行方法;
    proxy.eatFood();

 

代理模式及实现

原文:https://www.cnblogs.com/walker993/p/9439619.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!