Java代理和动态代理

code from 《Thinking in java》

 

代理模式

interface Interface {
    void doSomething();
    void somethingElse(String arg);
}

class RealObject implements Interface {

    @Override
    public void doSomething() {
        System.out.println("doSomething.");
    }

    @Override
    public void somethingElse(String arg) {
        System.out.println("somethingElse " + arg);
    }
}

class SimpleProxy implements Interface {

    private Interface proxy;

    public SimpleProxy(Interface proxy) {
        this.proxy = proxy;
    }

    @Override
    public void doSomething() {
        System.out.println("SimpleProxy doSomething.");
        proxy.doSomething();
    }

    @Override
    public void somethingElse(String arg) {
        System.out.println("SimpleProxy somethingElse " + arg);
        proxy.somethingElse(arg);
    }
}

public class SimpleProxyDemo {

    public static void consumer(Interface iface) {
        iface.doSomething();
        iface.somethingElse("bonobo");
    }

    public static void main(String[] args) {
        consumer(new RealObject());
        consumer(new SimpleProxy(new RealObject()));
    }

}

 


输出:

doSomething.
somethingElse bonobo
SimpleProxy doSomething.
doSomething.
SimpleProxy somethingElse bonobo
somethingElse bonobo

 

动态代理

class DynamicProxyHandler implements InvocationHandler {

    private Object proxy;

    public DynamicProxyHandler(Object proxy) {
        this.proxy = proxy;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("*** proxy: " + proxy.getClass() +
                ". method: " + method + ". args: " + args);
        if(args != null) {
            for(Object arg : args)
                System.out.println(" " + arg);
        }
        return method.invoke(this.proxy, args);
    }
}

public class SimpleDynamicProxy {

    public static void consumer(Interface iface) {
        iface.doSomething();
        iface.somethingElse("bonobo");
    }

    public static void main(String[] args) {
        RealObject real = new RealObject();
        consumer(real);
        // insert a proxy and call again:
        Interface proxy = (Interface)Proxy.newProxyInstance(
                Interface.class.getClassLoader(), 
                new Class[]{ Interface.class },
                new DynamicProxyHandler(real));

        consumer(proxy);
    }

}

输出:

doSomething.
somethingElse bonobo
*** proxy: class typeinfo.\$Proxy0. method: public abstract void typeinfo.Interface.doSomething(). args: null
doSomething.
*** proxy: class typeinfo.\$Proxy0. method: public abstract void typeinfo.Interface.somethingElse(java.lang.String). args: [Ljava.lang.Object;@6a8814e9
bonobo
somethingElse bonobo

 

 

二者最大的区别 动态代理 将代理类和实际执行类 解耦了  

代理类持有的是Object类型的引用 也就是说此时该代理类可以代理不同类型的实际执行类  

只需要在客户端实例化不同的实际执行类 再传入代理类中即可 

 

key thinking :解耦

 

posted @ 2016-08-15 15:31  丨核桃牛奶  阅读(127)  评论(0编辑  收藏  举报