国产色频,国产网站精品,成人在线综合网,精品一区二区三区毛片,亚洲无卡视频,黄色av观看,亚洲福利影视

設(shè)計模式 — 動態(tài)代理模式

2018-03-14 14:24:01 csdn  點擊量: 評論 (0)
動態(tài)代理動態(tài)代理0 簡介1 類圖2 示例3 源碼分析0 簡介代理模式有兩種形式:靜態(tài)代理、動態(tài)代理。1 類圖圖片來源網(wǎng)絡(luò)2 示例使

動態(tài)代理

 

 

 

0. 簡介

 

代理模式有兩種形式:靜態(tài)代理、動態(tài)代理。

1. 類圖

 

圖片來源網(wǎng)絡(luò) 
這里寫圖片描述

2. 示例

 

使用JDK中的Proxy類實現(xiàn)動態(tài)代理類的創(chuàng)建;

Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler handler);
  • 1

一般的用法:

public void proxy() throws Exception {
    PlayProxy handler= new PlayProxy();
    IPlay  proxy= (IPlay) Proxy.newProxyInstance(IPlay.class.getClassLoader(), new Class[]{IPlay.class}, handler);
    // 這個方法返回值為null,這是由invoke()方法返回的。
    proxy.play("籃球");
}

interface IPlay {
    void play(String name);
}

class PlayProxy implements InvocationHandler {

    // 當IPlay.play()被調(diào)用時,invoke()也會被調(diào)用。
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("method=" + method + " , args=" + args[0]);
        // 在此處直接添加處理邏輯。
        return null;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

輸出結(jié)果:

method=public abstract void com.example.demo.IPlay.play(java.lang.String) , args=籃球


由上面可以看出,雖然動態(tài)代理生成了接口的代理對象,但是代理類中沒有實際的處理邏輯,而接口的方法也是沒有實際處理邏輯的,所以要添加處理邏輯,只能在PlayProxy.invoke()中添加,這就增加了代碼的耦合性。

注意: 跟靜態(tài)代理相比,動態(tài)代理要少寫一個代理類,因為該代理類可以通過Proxy.newProxyInstance() 方法獲得。 
這里涉及到三個類: 
1. IPlay 
2. StudentPlay 
3. PlayProxy

public void proxy() throws Exception {
    StudentPlay student = new StudentPlay();
    PlayProxy handler= new PlayProxy(student);
    IPlay proxy= (IPlay) Proxy.newProxyInstance(IPlay.class.getClassLoader(), new Class[]{IPlay.class}, handler);
    proxy.play("籃球");//代理類執(zhí)行play()方法
}

interface IPlay {
    void play(String name);
}

class StudentPlay implements IPlay {
    @Override
    public void play(String name) {
        System.out.println("StudentPlay.play(),name=" + name);
    }
}

class PlayProxy<T> implements InvocationHandler {
    // 實際的執(zhí)行對象
    T target;
    public PlayProxy(T target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("method=" + method + " , args=" + args[0]);
        // 這里實際調(diào)用的是target對象中對應(yīng)的方法,即StudentPlay.play("籃球");
        Object result = method.invoke(target, args);
        return result;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

輸出結(jié)果:

method=public abstract void com.example.demo.IPlay.play(java.lang.String) , args=籃球 
StudentPlay.play(),name=籃球

3. 源碼分析

 

源碼基于JDK1.8

// java.lang.reflect.Proxy
public class Proxy implements java.io.Serializable {
    /** parameter types of a proxy class constructor */
    private static final Class<?>[] constructorParams = { InvocationHandler.class };

    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h) throws IllegalArgumentException {
        Objects.requireNonNull(h);

        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        // 1.獲取一個對interfaces包裝后的代理class
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }
            // 2.將InvocationHandler.class作為代理class的構(gòu)造參數(shù)
            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            // 3.通過構(gòu)造器創(chuàng)建代理class的實例對象Proxy,該Proxy對象內(nèi)持有一個InvocationHandler實例。
            return cons.newInstance(new Object[]{h});
        } catch (Exception e) {
            // ...代碼省略...
        }
    }
}
大云網(wǎng)官方微信售電那點事兒

責任編輯:售電衡衡

免責聲明:本文僅代表作者個人觀點,與本站無關(guān)。其原創(chuàng)性以及文中陳述文字和內(nèi)容未經(jīng)本站證實,對本文以及其中全部或者部分內(nèi)容、文字的真實性、完整性、及時性本站不作任何保證或承諾,請讀者僅作參考,并請自行核實相關(guān)內(nèi)容。
我要收藏
個贊
?