設(shè)計模式之——代理模式

1 代理模式的定義

代理模式:代理模式又叫委托模式读恃,是為某個對象提供一個代理對象招盲,并且由代理對象控制對原對象的訪問。代理模式通俗來講就是我們生活中常見的中介纺涤。
代理模式可以提供非常好的訪問控制桦锄,應(yīng)用比較廣泛。
舉個例子來說明:假如說我現(xiàn)在想買一輛二手車蔫耽,雖然我可以自己去找車源结耀,做質(zhì)量檢測等一系列的車輛過戶流程留夜,但是這確實(shí)太浪費(fèi)我得時間和精力了。我只是想買一輛車而已為什么我還要額外做這么多事呢图甜?于是我就通過中介公司來買車碍粥,他們來給我找車源,幫我辦理車輛過戶流程黑毅,我只是負(fù)責(zé)選擇自己喜歡的車嚼摩,然后付錢就可以了。

代理模式的通用類圖:


代理模式的通用類圖
  • Subject
    抽象主題角色:可以是抽象類矿瘦,也可以是接口枕面。抽象主題是一個普通的業(yè)務(wù)類型,無特殊要求缚去。
  • RealSubject
    具體主題角色:也叫做被委托角色被代理角色潮秘,是業(yè)務(wù)邏輯的具體執(zhí)行者。
  • Proxy
    代理主題角色:也叫做委托類代理類易结。它負(fù)責(zé)對真實(shí)角色的應(yīng)用枕荞,把所有抽象主題類定義的方法限制委托給真實(shí)主題角色實(shí)現(xiàn),并且在具體主題角色處理完畢前后做預(yù)處理和善后處理工作搞动。

一個代理類可以代理多個被委托者或被代理者躏精,因此一個代理類具體代理哪個具體主題角色,是由場景類決定的鹦肿。最簡單的情況是一個主題類和一個代理類矗烛。通常情況下,一個接口只需要一個代理類狮惜,具體代理哪個實(shí)現(xiàn)類有高層模塊決定高诺。

2 代理模式的優(yōu)點(diǎn)

  1. 職責(zé)清晰
    具體角色是實(shí)現(xiàn)具體的業(yè)務(wù)邏輯,不用關(guān)心其他非本職責(zé)的事務(wù)碾篡,通過后期的代理完成一件事務(wù)虱而,代碼清晰。在某些情況下开泽,一個客戶類不想或者不能直接引用一個委托對象牡拇,而代理類對象可以在客戶類和委托對象之間起到中介的作用,其特征是代理類和委托類實(shí)現(xiàn)相同的接口穆律。

  2. 高擴(kuò)展性
    具體主題角色隨時會發(fā)生變化吵瞻,但是只要實(shí)現(xiàn)了接口丈氓,接口不變,代理類就可以不做任何修改繼續(xù)使用,符合“開閉原則”齐邦。
    另外,代理類除了是客戶類和委托類的中介之外浪感,我們還可以通過給代理類增加額外的功能來擴(kuò)展委托類的功能,這樣做我們只需要修改代理類而不需要再修改委托類少梁,同樣符合開閉原則

  3. 智能化待完善
    動態(tài)代理的智能化

3 代理模式的使用場景

代理類主要負(fù)責(zé)為委托類預(yù)處理消息矫付、過濾消息凯沪、把消息轉(zhuǎn)發(fā)給委托類,以及事后對返回結(jié)果的處理等买优。代理類本身并不真正實(shí)現(xiàn)服務(wù)妨马,而是通過調(diào)用委托類的相關(guān)方法,來提供特定的服務(wù)杀赢。真正的業(yè)務(wù)功能還是由委托類來實(shí)現(xiàn)烘跺,但是可以在業(yè)務(wù)功能執(zhí)行的前后加入一些公共的服務(wù)。例如我們想給項(xiàng)目加入緩存葵陵、日志這些功能液荸,我們就可以使用代理類來完成,而沒必要打開已經(jīng)封裝好的委托類脱篙。

4 代理模式通用示例

為了保持行為的一致性娇钱,代理類和委托類通常會實(shí)現(xiàn)相同的接口,所以在訪問者看來兩者沒有絲毫的區(qū)別绊困。通過代理類這中間一層文搂,能有效控制對委托類對象的直接訪問,也可以很好地隱藏和保護(hù)委托類對象秤朗,同時也為實(shí)施不同控制策略預(yù)留了空間煤蹭,從而在設(shè)計上獲得了更大的靈活性。
更通俗的說取视,代理解決的問題是:當(dāng)兩個類需要通信時硝皂,引入第三方代理類,將兩個類的關(guān)系解耦作谭,讓我們只了解代理類即可稽物,而且代理的出現(xiàn)還可以讓我們完成與另一個類之間的關(guān)系的統(tǒng)一管理。但是切記折欠,代理類和委托類要實(shí)現(xiàn)相同的接口贝或,因?yàn)榇碚嬲{(diào)用的還是委托類的方法。

代理模式有多種不同的實(shí)現(xiàn)方式锐秦。如果按照代理創(chuàng)建的時期來進(jìn)行分類:靜態(tài)代理咪奖、動態(tài)代理

  • 靜態(tài)代理
    由程序員創(chuàng)建或特定工具自動生成源代碼酱床,再對其進(jìn)行編譯羊赵。在程序運(yùn)行之前,代理類.class文件就已經(jīng)被創(chuàng)建扇谣,代理類和委托類的關(guān)系在運(yùn)行前就確定昧捷。
  • 動態(tài)代理
    動態(tài)代理類的源碼是在程序運(yùn)行期間由JVM根據(jù)反射等機(jī)制動態(tài)的生成揖闸,所以不存在代理類的字節(jié)碼文件。代理類和委托類的關(guān)系是在程序運(yùn)行時確定料身。

4.1 靜態(tài)代理

  1. 抽象主題類
public interface Subject {
    /**
     * 接口方法
     */
    public void request();
}
  1. 具體主題類
public class ConcreteSubject implements Subject {
    /**
     * 具體的業(yè)務(wù)邏輯實(shí)現(xiàn)
     */
    @Override
    public void request() {
        //業(yè)務(wù)處理邏輯
    }
}
  1. 代理類
public class Proxy implements Subject {

    /**
     * 要代理的實(shí)現(xiàn)類
     */
    private Subject subject = null;

    /**
     * 默認(rèn)代理自己
     */
    public Proxy() {
        this.subject = new Proxy();
    }

    public Proxy(Subject subject) {
        this.subject = subject;
    }

    /**
     * 構(gòu)造函數(shù),傳遞委托者
     *
     * @param objects 委托者
     */
    public Proxy(Object... objects) {
    }

    /**
     * 實(shí)現(xiàn)接口方法
     */
    @Override
    public void request() {
        this.before();
        this.subject.request();
        this.after();
    }

    /**
     * 預(yù)處理
     */
    private void before() {
        //do something
    }

    /**
     * 后處理
     */
    private void after() {
        //do something
    }
}
  1. 客戶端類
public class Client {
    public static void main(String[] args) {
        Subject subject = new ConcreteSubject();
        Proxy proxy = new Proxy(subject);
        proxy.request();
    }
}
  1. 靜態(tài)代理優(yōu)缺點(diǎn)
  • 優(yōu)點(diǎn)
    業(yè)務(wù)類只需要關(guān)注業(yè)務(wù)邏輯本身衩茸,保證了業(yè)務(wù)類的重用性芹血。這是代理的共有優(yōu)點(diǎn)。代理使客戶端不需要知道實(shí)現(xiàn)類是什么楞慈,怎么做的幔烛,而客戶端只需知道代理即可(解耦合)。對于如上的客戶端代碼囊蓝,Subject subject = new ConcreteSubject(); Proxy proxy = new Proxy(subject);可以應(yīng)用工廠方法將它隱藏饿悬。
  • 缺點(diǎn)
    • 代理類和委托類實(shí)現(xiàn)了相同的接口,代理類通過委托類實(shí)現(xiàn)了相同的方法聚霜。這樣就出現(xiàn)了大量的代碼重復(fù)狡恬。如果接口增加一個方法,除了所有實(shí)現(xiàn)類需要實(shí)現(xiàn)這個方法外蝎宇,所有代理類也需要實(shí)現(xiàn)此方法弟劲。增加了代碼維護(hù)的復(fù)雜度。
    • 代理對象只服務(wù)于一種類型的對象姥芥,如果要服務(wù)多類型的對象兔乞。勢必要為每一種對象都進(jìn)行代理,靜態(tài)代理在程序規(guī)模稍大時就無法勝任了凉唐。如上的代碼是只為Subject類的訪問提供了代理庸追,但是如果還要為其他類如AnotherSubject類提供代理的話,就需要我們再次添加代理AnotherSubject的代理類台囱。
      由于靜態(tài)代理的這個缺點(diǎn)淡溯,就需要使用動態(tài)代理。

4.2 動態(tài)代理

從靜態(tài)代理會發(fā)現(xiàn)——每個代理類只能為一個接口服務(wù)玄坦,這樣程序開發(fā)中必然會產(chǎn)生許多的代理類血筑。所以我們想辦法通過一個代理類完成全部的代理功能,那么我們就需要用動態(tài)代理.
在上面4.1的示例中煎楣,一個代理只能代理一種類型豺总,而且是在編譯器就已經(jīng)確定被代理的對象。而動態(tài)代理是在運(yùn)行時择懂,通過反射機(jī)制實(shí)現(xiàn)動態(tài)代理喻喳,并且能夠代理各種類型的對象
在Java中要想實(shí)現(xiàn)動態(tài)代理機(jī)制困曙,需要java.lang.reflect.InvocationHandler接口和 java.lang.reflect.Proxy類的支持表伦。

  1. java.lang.reflect.InvocationHandler接口的定義
package java.lang.reflect;
public interface InvocationHandler {

    /**
     * Processes a method invocation on a proxy instance and returns
     * the result.  This method will be invoked on an invocation handler
     * when a method is invoked on a proxy instance that it is
     * associated with.
     *
     * @param   proxy the proxy instance that the method was invoked on
     *
     * @param   method the {@code Method} instance corresponding to
     * the interface method invoked on the proxy instance.  The declaring
     * class of the {@code Method} object will be the interface that
     * the method was declared in, which may be a superinterface of the
     * proxy interface that the proxy class inherits the method through.
     *
     * @param   args an array of objects containing the values of the
     * arguments passed in the method invocation on the proxy instance,
     * or {@code null} if interface method takes no arguments.
     * Arguments of primitive types are wrapped in instances of the
     * appropriate primitive wrapper class, such as
     * {@code java.lang.Integer} or {@code java.lang.Boolean}.
     *
     * @return  the value to return from the method invocation on the
     * proxy instance.  If the declared return type of the interface
     * method is a primitive type, then the value returned by
     * this method must be an instance of the corresponding primitive
     * wrapper class; otherwise, it must be a type assignable to the
     * declared return type.  If the value returned by this method is
     * {@code null} and the interface method's return type is
     * primitive, then a {@code NullPointerException} will be
     * thrown by the method invocation on the proxy instance.  If the
     * value returned by this method is otherwise not compatible with
     * the interface method's declared return type as described above,
     * a {@code ClassCastException} will be thrown by the method
     * invocation on the proxy instance.
     *
     * @throws  Throwable the exception to throw from the method
     * invocation on the proxy instance.  The exception's type must be
     * assignable either to any of the exception types declared in the
     * {@code throws} clause of the interface method or to the
     * unchecked exception types {@code java.lang.RuntimeException}
     * or {@code java.lang.Error}.  If a checked exception is
     * thrown by this method that is not assignable to any of the
     * exception types declared in the {@code throws} clause of
     * the interface method, then an
     * {@link UndeclaredThrowableException} containing the
     * exception that was thrown by this method will be thrown by the
     * method invocation on the proxy instance.
     *
     * @see     UndeclaredThrowableException
     */
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;
}

參數(shù)解釋:

  • Object proxy
    被代理對象
  • Method method
    要調(diào)用的方法
  • Object[] args
    方法調(diào)用時所需要的參數(shù)
  1. java.lang.reflect.Proxy類的定義
public class Proxy implements java.io.Serializable {

    private static final long serialVersionUID = -2222568056686623797L;

    /** parameter types of a proxy class constructor */
    private static final Class<?>[] constructorParams =
        { InvocationHandler.class };

    /**
     * a cache of proxy classes
     */
    private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

    /**
     * the invocation handler for this proxy instance.
     * @serial
     */
    protected InvocationHandler h;

    /**
     * Prohibits instantiation.
     */
    private Proxy() {
    }

    /**
     * Constructs a new {@code Proxy} instance from a subclass
     * (typically, a dynamic proxy class) with the specified value
     * for its invocation handler.
     *
     * @param  h the invocation handler for this proxy instance
     *
     * @throws NullPointerException if the given invocation handler, {@code h},
     *         is {@code null}.
     */
    protected Proxy(InvocationHandler h) {
        Objects.requireNonNull(h);
        this.h = h;
    }

    /**
     * Returns the {@code java.lang.Class} object for a proxy class
     * given a class loader and an array of interfaces.  The proxy class
     * will be defined by the specified class loader and will implement
     * all of the supplied interfaces.  If any of the given interfaces
     * is non-public, the proxy class will be non-public. If a proxy class
     * for the same permutation of interfaces has already been defined by the
     * class loader, then the existing proxy class will be returned; otherwise,
     * a proxy class for those interfaces will be generated dynamically
     * and defined by the class loader.
     *
     * <p>There are several restrictions on the parameters that may be
     * passed to {@code Proxy.getProxyClass}:
     *
     * <ul>
     * <li>All of the {@code Class} objects in the
     * {@code interfaces} array must represent interfaces, not
     * classes or primitive types.
     *
     * <li>No two elements in the {@code interfaces} array may
     * refer to identical {@code Class} objects.
     *
     * <li>All of the interface types must be visible by name through the
     * specified class loader.  In other words, for class loader
     * {@code cl} and every interface {@code i}, the following
     * expression must be true:
     * <pre>
     *     Class.forName(i.getName(), false, cl) == i
     * </pre>
     *
     * <li>All non-public interfaces must be in the same package;
     * otherwise, it would not be possible for the proxy class to
     * implement all of the interfaces, regardless of what package it is
     * defined in.
     *
     * <li>For any set of member methods of the specified interfaces
     * that have the same signature:
     * <ul>
     * <li>If the return type of any of the methods is a primitive
     * type or void, then all of the methods must have that same
     * return type.
     * <li>Otherwise, one of the methods must have a return type that
     * is assignable to all of the return types of the rest of the
     * methods.
     * </ul>
     *
     * <li>The resulting proxy class must not exceed any limits imposed
     * on classes by the virtual machine.  For example, the VM may limit
     * the number of interfaces that a class may implement to 65535; in
     * that case, the size of the {@code interfaces} array must not
     * exceed 65535.
     * </ul>
     *
     * <p>If any of these restrictions are violated,
     * {@code Proxy.getProxyClass} will throw an
     * {@code IllegalArgumentException}.  If the {@code interfaces}
     * array argument or any of its elements are {@code null}, a
     * {@code NullPointerException} will be thrown.
     *
     * <p>Note that the order of the specified proxy interfaces is
     * significant: two requests for a proxy class with the same combination
     * of interfaces but in a different order will result in two distinct
     * proxy classes.
     *
     * @param   loader the class loader to define the proxy class
     * @param   interfaces the list of interfaces for the proxy class
     *          to implement
     * @return  a proxy class that is defined in the specified class loader
     *          and that implements the specified interfaces
     * @throws  IllegalArgumentException if any of the restrictions on the
     *          parameters that may be passed to {@code getProxyClass}
     *          are violated
     * @throws  SecurityException if a security manager, <em>s</em>, is present
     *          and any of the following conditions is met:
     *          <ul>
     *             <li> the given {@code loader} is {@code null} and
     *             the caller's class loader is not {@code null} and the
     *             invocation of {@link SecurityManager#checkPermission
     *             s.checkPermission} with
     *             {@code RuntimePermission("getClassLoader")} permission
     *             denies access.</li>
     *             <li> for each proxy interface, {@code intf},
     *             the caller's class loader is not the same as or an
     *             ancestor of the class loader for {@code intf} and
     *             invocation of {@link SecurityManager#checkPackageAccess
     *             s.checkPackageAccess()} denies access to {@code intf}.</li>
     *          </ul>

     * @throws  NullPointerException if the {@code interfaces} array
     *          argument or any of its elements are {@code null}
     */
    @CallerSensitive
    public static Class<?> getProxyClass(ClassLoader loader,
                                         Class<?>... interfaces)
        throws IllegalArgumentException
    {
        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        return getProxyClass0(loader, intfs);
    }

    /*
     * Check permissions required to create a Proxy class.
     *
     * To define a proxy class, it performs the access checks as in
     * Class.forName (VM will invoke ClassLoader.checkPackageAccess):
     * 1. "getClassLoader" permission check if loader == null
     * 2. checkPackageAccess on the interfaces it implements
     *
     * To get a constructor and new instance of a proxy class, it performs
     * the package access check on the interfaces it implements
     * as in Class.getConstructor.
     *
     * If an interface is non-public, the proxy class must be defined by
     * the defining loader of the interface.  If the caller's class loader
     * is not the same as the defining loader of the interface, the VM
     * will throw IllegalAccessError when the generated proxy class is
     * being defined via the defineClass0 method.
     */
    private static void checkProxyAccess(Class<?> caller,
                                         ClassLoader loader,
                                         Class<?>... interfaces)
    {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            ClassLoader ccl = caller.getClassLoader();
            if (VM.isSystemDomainLoader(loader) && !VM.isSystemDomainLoader(ccl)) {
                sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
            }
            ReflectUtil.checkProxyPackageAccess(ccl, interfaces);
        }
    }

    /**
     * Generate a proxy class.  Must call the checkProxyAccess method
     * to perform permission checks before calling this.
     */
    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }

        // If the proxy class defined by the given loader implementing
        // the given interfaces exists, this will simply return the cached copy;
        // otherwise, it will create the proxy class via the ProxyClassFactory
        return proxyClassCache.get(loader, interfaces);
    }

    /*
     * a key used for proxy class with 0 implemented interfaces
     */
    private static final Object key0 = new Object();

    /*
     * Key1 and Key2 are optimized for the common use of dynamic proxies
     * that implement 1 or 2 interfaces.
     */

    /*
     * a key used for proxy class with 1 implemented interface
     */
    private static final class Key1 extends WeakReference<Class<?>> {
        private final int hash;

        Key1(Class<?> intf) {
            super(intf);
            this.hash = intf.hashCode();
        }

        @Override
        public int hashCode() {
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            Class<?> intf;
            return this == obj ||
                   obj != null &&
                   obj.getClass() == Key1.class &&
                   (intf = get()) != null &&
                   intf == ((Key1) obj).get();
        }
    }

    /*
     * a key used for proxy class with 2 implemented interfaces
     */
    private static final class Key2 extends WeakReference<Class<?>> {
        private final int hash;
        private final WeakReference<Class<?>> ref2;

        Key2(Class<?> intf1, Class<?> intf2) {
            super(intf1);
            hash = 31 * intf1.hashCode() + intf2.hashCode();
            ref2 = new WeakReference<Class<?>>(intf2);
        }

        @Override
        public int hashCode() {
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            Class<?> intf1, intf2;
            return this == obj ||
                   obj != null &&
                   obj.getClass() == Key2.class &&
                   (intf1 = get()) != null &&
                   intf1 == ((Key2) obj).get() &&
                   (intf2 = ref2.get()) != null &&
                   intf2 == ((Key2) obj).ref2.get();
        }
    }

    /*
     * a key used for proxy class with any number of implemented interfaces
     * (used here for 3 or more only)
     */
    private static final class KeyX {
        private final int hash;
        private final WeakReference<Class<?>>[] refs;

        @SuppressWarnings("unchecked")
        KeyX(Class<?>[] interfaces) {
            hash = Arrays.hashCode(interfaces);
            refs = (WeakReference<Class<?>>[])new WeakReference<?>[interfaces.length];
            for (int i = 0; i < interfaces.length; i++) {
                refs[i] = new WeakReference<>(interfaces[i]);
            }
        }

        @Override
        public int hashCode() {
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            return this == obj ||
                   obj != null &&
                   obj.getClass() == KeyX.class &&
                   equals(refs, ((KeyX) obj).refs);
        }

        private static boolean equals(WeakReference<Class<?>>[] refs1,
                                      WeakReference<Class<?>>[] refs2) {
            if (refs1.length != refs2.length) {
                return false;
            }
            for (int i = 0; i < refs1.length; i++) {
                Class<?> intf = refs1[i].get();
                if (intf == null || intf != refs2[i].get()) {
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * A function that maps an array of interfaces to an optimal key where
     * Class objects representing interfaces are weakly referenced.
     */
    private static final class KeyFactory
        implements BiFunction<ClassLoader, Class<?>[], Object>
    {
        @Override
        public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
            switch (interfaces.length) {
                case 1: return new Key1(interfaces[0]); // the most frequent
                case 2: return new Key2(interfaces[0], interfaces[1]);
                case 0: return key0;
                default: return new KeyX(interfaces);
            }
        }
    }

    /**
     * A factory function that generates, defines and returns the proxy class given
     * the ClassLoader and array of interfaces.
     */
    private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names
        private static final String proxyClassNamePrefix = "$Proxy";

        // next number to use for generation of unique proxy class names
        private static final AtomicLong nextUniqueNumber = new AtomicLong();

        @Override
        public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
            for (Class<?> intf : interfaces) {
                /*
                 * Verify that the class loader resolves the name of this
                 * interface to the same Class object.
                 */
                Class<?> interfaceClass = null;
                try {
                    interfaceClass = Class.forName(intf.getName(), false, loader);
                } catch (ClassNotFoundException e) {
                }
                if (interfaceClass != intf) {
                    throw new IllegalArgumentException(
                        intf + " is not visible from class loader");
                }
                /*
                 * Verify that the Class object actually represents an
                 * interface.
                 */
                if (!interfaceClass.isInterface()) {
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                /*
                 * Verify that this interface is not a duplicate.
                 */
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }

            String proxyPkg = null;     // package to define proxy class in
            int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

            /*
             * Record the package of a non-public proxy interface so that the
             * proxy class will be defined in the same package.  Verify that
             * all non-public proxy interfaces are in the same package.
             */
            for (Class<?> intf : interfaces) {
                int flags = intf.getModifiers();
                if (!Modifier.isPublic(flags)) {
                    accessFlags = Modifier.FINAL;
                    String name = intf.getName();
                    int n = name.lastIndexOf('.');
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use com.sun.proxy package
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                /*
                 * A ClassFormatError here means that (barring bugs in the
                 * proxy class generation code) there was some other
                 * invalid aspect of the arguments supplied to the proxy
                 * class creation (such as virtual machine limitations
                 * exceeded).
                 */
                throw new IllegalArgumentException(e.toString());
            }
        }
    }

    /**
     * Returns an instance of a proxy class for the specified interfaces
     * that dispatches method invocations to the specified invocation
     * handler.
     *
     * <p>{@code Proxy.newProxyInstance} throws
     * {@code IllegalArgumentException} for the same reasons that
     * {@code Proxy.getProxyClass} does.
     *
     * @param   loader the class loader to define the proxy class
     * @param   interfaces the list of interfaces for the proxy class
     *          to implement
     * @param   h the invocation handler to dispatch method invocations to
     * @return  a proxy instance with the specified invocation handler of a
     *          proxy class that is defined by the specified class loader
     *          and that implements the specified interfaces
     * @throws  IllegalArgumentException if any of the restrictions on the
     *          parameters that may be passed to {@code getProxyClass}
     *          are violated
     * @throws  SecurityException if a security manager, <em>s</em>, is present
     *          and any of the following conditions is met:
     *          <ul>
     *          <li> the given {@code loader} is {@code null} and
     *               the caller's class loader is not {@code null} and the
     *               invocation of {@link SecurityManager#checkPermission
     *               s.checkPermission} with
     *               {@code RuntimePermission("getClassLoader")} permission
     *               denies access;</li>
     *          <li> for each proxy interface, {@code intf},
     *               the caller's class loader is not the same as or an
     *               ancestor of the class loader for {@code intf} and
     *               invocation of {@link SecurityManager#checkPackageAccess
     *               s.checkPackageAccess()} denies access to {@code intf};</li>
     *          <li> any of the given proxy interfaces is non-public and the
     *               caller class is not in the same {@linkplain Package runtime package}
     *               as the non-public interface and the invocation of
     *               {@link SecurityManager#checkPermission s.checkPermission} with
     *               {@code ReflectPermission("newProxyInPackage.{package name}")}
     *               permission denies access.</li>
     *          </ul>
     * @throws  NullPointerException if the {@code interfaces} array
     *          argument or any of its elements are {@code null}, or
     *          if the invocation handler, {@code h}, is
     *          {@code null}
     */
    @CallerSensitive
    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);
        }

        /*
         * Look up or generate the designated proxy class.
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            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;
                    }
                });
            }
            return cons.newInstance(new Object[]{h});
        } catch (IllegalAccessException|InstantiationException e) {
            throw new InternalError(e.toString(), e);
        } catch (InvocationTargetException e) {
            Throwable t = e.getCause();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new InternalError(t.toString(), t);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString(), e);
        }
    }

    private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {
                ClassLoader ccl = caller.getClassLoader();
                ClassLoader pcl = proxyClass.getClassLoader();

                // do permission check if the caller is in a different runtime package
                // of the proxy class
                int n = proxyClass.getName().lastIndexOf('.');
                String pkg = (n == -1) ? "" : proxyClass.getName().substring(0, n);

                n = caller.getName().lastIndexOf('.');
                String callerPkg = (n == -1) ? "" : caller.getName().substring(0, n);

                if (pcl != ccl || !pkg.equals(callerPkg)) {
                    sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
                }
            }
        }
    }

    /**
     * Returns true if and only if the specified class was dynamically
     * generated to be a proxy class using the {@code getProxyClass}
     * method or the {@code newProxyInstance} method.
     *
     * <p>The reliability of this method is important for the ability
     * to use it to make security decisions, so its implementation should
     * not just test if the class in question extends {@code Proxy}.
     *
     * @param   cl the class to test
     * @return  {@code true} if the class is a proxy class and
     *          {@code false} otherwise
     * @throws  NullPointerException if {@code cl} is {@code null}
     */
    public static boolean isProxyClass(Class<?> cl) {
        return Proxy.class.isAssignableFrom(cl) && proxyClassCache.containsValue(cl);
    }

    /**
     * Returns the invocation handler for the specified proxy instance.
     *
     * @param   proxy the proxy instance to return the invocation handler for
     * @return  the invocation handler for the proxy instance
     * @throws  IllegalArgumentException if the argument is not a
     *          proxy instance
     * @throws  SecurityException if a security manager, <em>s</em>, is present
     *          and the caller's class loader is not the same as or an
     *          ancestor of the class loader for the invocation handler
     *          and invocation of {@link SecurityManager#checkPackageAccess
     *          s.checkPackageAccess()} denies access to the invocation
     *          handler's class.
     */
    @CallerSensitive
    public static InvocationHandler getInvocationHandler(Object proxy)
        throws IllegalArgumentException
    {
        /*
         * Verify that the object is actually a proxy instance.
         */
        if (!isProxyClass(proxy.getClass())) {
            throw new IllegalArgumentException("not a proxy instance");
        }

        final Proxy p = (Proxy) proxy;
        final InvocationHandler ih = p.h;
        if (System.getSecurityManager() != null) {
            Class<?> ihClass = ih.getClass();
            Class<?> caller = Reflection.getCallerClass();
            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                    ihClass.getClassLoader()))
            {
                ReflectUtil.checkPackageAccess(ihClass);
            }
        }

        return ih;
    }

    private static native Class<?> defineClass0(ClassLoader loader, String name,
                                                byte[] b, int off, int len);
}

其中谦去,最重要的方法是

    @CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException

參數(shù)說明:

  • ClassLoader loader
    類的加載器
  • Class<?>[] interfaces
    得到全部的接口
  • InvocationHandler h
    得到InvocationHandler接口的子類的實(shí)例
  1. 抽象主題類
public interface Subject {
    /**
     * 接口方法
     */
    public void request();
}
  1. 具體主題類
public class ConcreteSubject implements Subject {
    /**
     * 具體的業(yè)務(wù)邏輯實(shí)現(xiàn)
     */
    @Override
    public void request() {
        //業(yè)務(wù)處理邏輯
    }
}
  1. 動態(tài)創(chuàng)建代理對象的類
    動態(tài)代理類只能代理接口(不支持抽象類),代理類都需要實(shí)現(xiàn)InvocationHandler類蹦哼,實(shí)現(xiàn)invoke方法鳄哭。invoke方法就是調(diào)用被代理接口的所有方法時需要調(diào)用的,返回的值是被代理接口的一個實(shí)現(xiàn)類纲熏。
package com.jerry.microservice.cloud.service.proxy.dynamic;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author :DuLvJL
 * @date :23:07 2019/3/5
 * @description :insert the description of this class
 **/
@Slf4j
public class ProxyHandler implements InvocationHandler {
    /**
     * 目標(biāo)對象
     */
    private Object target;

    /**
     * 綁定關(guān)系妆丘,也就是關(guān)聯(lián)到哪個接口(與具體的實(shí)現(xiàn)類綁定)的哪些方法將被調(diào)用時,執(zhí)行invoke方法局劲。
     *
     * @param target 綁定具體的代理實(shí)例
     * @return 動態(tài)代理類實(shí)例
     */
    public Object newProxyInstance(Object target) {
        this.target = target;
        /*
        該方法用于為指定類裝載器勺拣、一組接口及調(diào)用處理器生成動態(tài)代理類實(shí)例。
        第一個參數(shù)指定產(chǎn)生代理對象的類加載器鱼填,需要將其指定為和目標(biāo)對象同一個類加載器药有。
        第二個參數(shù)要實(shí)現(xiàn)和目標(biāo)對象一樣的接口,所以只需要拿到目標(biāo)對象的實(shí)現(xiàn)接口苹丸。
        第三個參數(shù)表明這些被攔截的方法在被攔截時需要執(zhí)行哪個InvocationHandler的invoke方法
        根據(jù)傳入的目標(biāo)返回一個代理對象
        */
        Object result = Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
        return result;
    }

    /**
     * 關(guān)聯(lián)的這個實(shí)現(xiàn)類的方法被調(diào)用時將被執(zhí)行愤惰。InvocationHandler接口的方法。
     *
     * @param proxy  代理
     * @param method 原對象被調(diào)用的方法
     * @param args   方法的參數(shù)
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //TODO 原對象方法調(diào)用前添加的預(yù)處理邏輯

        Object ret = null;
        try {
            //調(diào)用目標(biāo)方法
            ret = method.invoke(target, args);
        } catch (Exception e) {
            log.error("調(diào)用{}.{}發(fā)生異常", target.getClass().getName(), method.getName(), e);
            throw e;
        }
        //TODO 原對象方法調(diào)用后添加的后處理邏輯
        return ret;
    }
}

被代理對象target通過參數(shù)傳遞進(jìn)來赘理,我們通過target.getClass().getClassLoader()獲取ClassLoader對象羊苟,然后通過target.getClass().getInterfaces()獲取它實(shí)現(xiàn)的所有接口,然后將target包裝到實(shí)現(xiàn)了InvocationHandler接口的ProxyHandler實(shí)現(xiàn)對象中感憾。通過newProxyInstance函數(shù)我們就獲得了一個動態(tài)代理對象蜡励。

  1. 客戶端類
@Slf4j
public class Client {
    public static void main(String[] args) {
        log.info("開始");
        ProxyHandler handler = new ProxyHandler();
        Subject subject = (Subject) handler.newProxyInstance(new ConcreteSubject());
        subject.request();
        log.info("結(jié)束");
    }
}

可以看到,我們可以通過ProxyHandler代理不同類型的對象阻桅,如果我們把對外的接口都通過動態(tài)代理來實(shí)現(xiàn)凉倚,那么所有的函數(shù)調(diào)用最終都會經(jīng)過invoke函數(shù)的轉(zhuǎn)發(fā),因此我們就可以在這里做一些自己想做的操作嫂沉,比如日志系統(tǒng)稽寒、事務(wù)、攔截器趟章、權(quán)限控制等杏糙。
當(dāng)前非常流行的面向切面的編程(Aspect Oriented Programming, AOP),其核心就是動態(tài)代理機(jī)制蚓土。
備注
要實(shí)現(xiàn)動態(tài)代理的首要條件:被代理類必須實(shí)現(xiàn)一個接口宏侍,才能被代理。
(現(xiàn)在還有CGLIB可以實(shí)現(xiàn)不用實(shí)現(xiàn)接口也可以實(shí)現(xiàn)動態(tài)代理蜀漆。后續(xù)研究)

  1. 動態(tài)代理的優(yōu)缺點(diǎn)
  • 優(yōu)點(diǎn)
    動態(tài)代理與靜態(tài)代理相比較谅河,最大的好處是接口中聲明的所有方法都被轉(zhuǎn)移到調(diào)用處理器一個集中的方法中處理(InvocationHandler.invoke)。這樣,在接口方法數(shù)量比較多的時候绷耍,我們可以進(jìn)行靈活處理吐限,而不需要像靜態(tài)代理那樣每一個方法進(jìn)行中轉(zhuǎn)。而且動態(tài)代理的應(yīng)用使我們的類職責(zé)更加單一褂始,復(fù)用性更強(qiáng)诸典。
  • 缺點(diǎn)
    Proxy已經(jīng)設(shè)計得非常優(yōu)美,但是還是有一點(diǎn)點(diǎn)小小的遺憾之處——它始終無法擺脫僅支持 interface代理的桎梏崎苗,因?yàn)樗脑O(shè)計注定了這個遺憾搂赋。動態(tài)生成的代理類的繼承關(guān)系圖,已經(jīng)注定有一個共同的父類叫 Proxy益缠。Java 的繼承機(jī)制注定了這些動態(tài)代理類們無法實(shí)現(xiàn)對 class 的動態(tài)代理,原因是多繼承在 Java 中本質(zhì)上就行不通基公。

8 總結(jié)

代理模式使用廣泛幅慌,尤其是動態(tài)代理在大型開發(fā)框架中,應(yīng)用較多并且高效轰豆。特別是使用AOP胰伍,實(shí)現(xiàn)代理模式就更方便了,比如使用Spring AOP和AspectJ這樣的工具酸休。
在使用AOP框架時骂租,需要關(guān)注幾個名詞:

  • 切面(Aspect)
  • 切入點(diǎn)(JointPoint)
  • 通知(Advice)
  • 織入(Weave)

參考

  1. 設(shè)計模式---代理模式
  2. 動態(tài)代理與靜態(tài)代理區(qū)別
  3. 設(shè)計模式之禪
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市斑司,隨后出現(xiàn)的幾起案子渗饮,更是在濱河造成了極大的恐慌,老刑警劉巖宿刮,帶你破解...
    沈念sama閱讀 211,561評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件互站,死亡現(xiàn)場離奇詭異,居然都是意外死亡僵缺,警方通過查閱死者的電腦和手機(jī)胡桃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,218評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來磕潮,“玉大人翠胰,你說我怎么就攤上這事∽愿” “怎么了之景?”我有些...
    開封第一講書人閱讀 157,162評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長膏潮。 經(jīng)常有香客問我闺兢,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,470評論 1 283
  • 正文 為了忘掉前任屋谭,我火速辦了婚禮脚囊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘桐磁。我一直安慰自己悔耘,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,550評論 6 385
  • 文/花漫 我一把揭開白布我擂。 她就那樣靜靜地躺著衬以,像睡著了一般。 火紅的嫁衣襯著肌膚如雪校摩。 梳的紋絲不亂的頭發(fā)上看峻,一...
    開封第一講書人閱讀 49,806評論 1 290
  • 那天,我揣著相機(jī)與錄音衙吩,去河邊找鬼互妓。 笑死,一個胖子當(dāng)著我的面吹牛坤塞,可吹牛的內(nèi)容都是我干的冯勉。 我是一名探鬼主播,決...
    沈念sama閱讀 38,951評論 3 407
  • 文/蒼蘭香墨 我猛地睜開眼摹芙,長吁一口氣:“原來是場噩夢啊……” “哼灼狰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起浮禾,我...
    開封第一講書人閱讀 37,712評論 0 266
  • 序言:老撾萬榮一對情侶失蹤交胚,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后盈电,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體承绸,經(jīng)...
    沈念sama閱讀 44,166評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,510評論 2 327
  • 正文 我和宋清朗相戀三年挣轨,在試婚紗的時候發(fā)現(xiàn)自己被綠了军熏。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,643評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡卷扮,死狀恐怖荡澎,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情晤锹,我是刑警寧澤摩幔,帶...
    沈念sama閱讀 34,306評論 4 330
  • 正文 年R本政府宣布,位于F島的核電站鞭铆,受9級特大地震影響或衡,放射性物質(zhì)發(fā)生泄漏焦影。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,930評論 3 313
  • 文/蒙蒙 一封断、第九天 我趴在偏房一處隱蔽的房頂上張望斯辰。 院中可真熱鬧,春花似錦坡疼、人聲如沸彬呻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,745評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽闸氮。三九已至,卻和暖如春教沾,著一層夾襖步出監(jiān)牢的瞬間蒲跨,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,983評論 1 266
  • 我被黑心中介騙來泰國打工授翻, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留或悲,地道東北人。 一個月前我還...
    沈念sama閱讀 46,351評論 2 360
  • 正文 我出身青樓藏姐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親该贾。 傳聞我的和親對象是個殘疾皇子羔杨,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,509評論 2 348

推薦閱讀更多精彩內(nèi)容