作者:京东零售 秦浩然

引子

举个栗子,众所周知,咱们是能够在京东上购买机票的。 但机票是航司供给的,咱们本质上是署理出售而已。

那为什么航司要让咱们署理出售呢?

咱们又是如帮他做署理的呢?

别急,本文将打开说说他们之间的联系。。。

一个有愿望的航司

早年有个航司打算开展线上出售机票事务,所以设计了如下体系。体系完结后,事务正常开展了。。。

航司出售机票的接口

public interface SellAirTicket {
    /**
     * 出售机票
     * @param price
     */
    void sellAirTicket(int price);
}

航司出售机票的接口完结类:

public class SellAirTicketImpl implements SellAirTicket {
    @Override
    public void sellAirTicket(int price) {
        System.out.println("航司出售机票,价格:" + price);
    }
}

测验:

public class MainClass {
    public static void main(String[] args) {
        SellAirTicket sellAirTicket = new SellAirTicketImpl();
        sellAirTicket.sellAirTicket(666);
    }
}

测验成果:

航司出售机票,价格:666

事务欣欣向荣,问题接踵而至

跟着事务发展的越来越好,新的问题呈现了。

黄牛天天爬接口,体系风险呈现了;卖完票没有计算成果,卖成啥样也不知道。

所以航司想增加售前风控、售后计算。加上这些功能后,事务又持续稳步发展了。。。

航司出售机票的接口:

public interface SellAirTicket {
    /**
     * 出售机票
     * @param price
     */
    void sellAirTicket(int price);
}

航司出售机票的接口完结类:

public class SellAirTicketImpl implements SellAirTicket {
    @Override
    public void sellAirTicket(int price) {
        System.out.println("航司售前风控。。。");
        System.out.println("航司出售机票,价格:" + price);
        System.out.println("航司售后计算。。。");
    }
}

测验:

public class MainClass {
    public static void main(String[] args) {
        SellAirTicket sellAirTicket = new SellAirTicketImpl();
        sellAirTicket.sellAirTicket(666);
    }
}

测验成果:

航司售前风控。。。
航司出售机票,价格:666
航司售后计算。。。   

人员捉襟见肘,事务被迫拆分

后来航司发现,就这么点人,又想做风控,又想卖机票,又想做计算,底子忙不过来。

那怎么处理呢? 航司只想专注卖票,不想做这些跟卖票无关的工作,那只能找个署理公司了。

所以,航司找到了JD替代自己做这些工作,自己就担任专注卖票。。。

航司出售机票的接口:

public interface SellAirTicket {
    /**
     * 出售机票
     * @param price
     */
    void sellAirTicket(int price);
}

航司出售机票的接口完结类:

public class SellAirTicketImpl implements SellAirTicket {
    @Override
    public void sellAirTicket(int price) {
        System.out.println("航司出售机票,价格:" + price);
    }
}

JD渠道署理航司出售机票完结类:

public class SellAirTicketProxy implements SellAirTicket {
    /**
     * 航司售票接口
     */
    private SellAirTicket sellAirTicket;
    @Override
    public void sellAirTicket(int price) {
        System.out.println("JD售前风控。。。");
        sellAirTicket.sellAirTicket(price);
        System.out.println("JD售后计算。。。");
    }
    public SellAirTicketProxy(SellAirTicket sellAirTicket) {
        this.sellAirTicket = sellAirTicket;
    }
}

测验:

public class MainClass {
    public static void main(String[] args) {
        SellAirTicket sellAirTicket = new SellAirTicketImpl();
        SellAirTicket sellAirTicketProxy = new SellAirTicketProxy(sellAirTicket);
        sellAirTicketProxy.sellAirTicket(666);
    }
}

测验成果:

JD售前风控。。。
航司出售机票,价格:666
JD售后计算。。。

朴素的1对1协作办法,静态署理

以上流程对与航司而言,由JD协助自己重视风控、计算,自已能够专注的卖票,看着很好的样子。

但是JD渠道只能给航司卖票,其他的也干不了,航司与JD的联系归于静态绑定的联系,即:被署理类与署理类归于静态绑定的联系,称之为“静态署理”。

据此,咱们能够给署理形式下个界说:

【署理形式】 便是在不改动原有类(被署理类)的情况下,为原有类创立署理方针,对原有类的功能做增强的一种形式
署理形式的优点:
1. 满意单一准则,事务类能够只关怀自己的中心逻辑,非中心逻辑由署理类完结;
2. 易于保护,中心逻辑、非中心逻辑的修正不会相互影响;
3. 关于用户(调用者)而言,运用的办法没有差异,有和能够做到低成本替换;
署理形式的缺陷:
1. 每个被署理类都要有一个署理类,大大增加了代码量;

稳妥呈现,署理公司高瞻远瞩

某天,稳妥公司也被风控、计算逻辑搞的焦头烂额,听说航司找了个署理,所以也找到了JD,让JD给他们做署理。

JD想:总不能谁来找我,我就给谁做一套署理体系吧,那我得做多少套,反正他们都是找我做风控、计算的,那我能不能做一套体系,给他们所有的人用呢,说干就干。。。

稳妥公司出售稳妥的接口:

public interface SellInsurance {
    /**
     * 出售稳妥
     * @param price
     */
    void sellInsurance(int price);
}

稳妥公司出售稳妥的接口完结类:

public class SellInsuranceImpl implements SellInsurance {
    @Override
    public void sellInsurance(int price) {
        System.out.println("稳妥公司出售稳妥,价格:" + price);
    }
}

JD渠道署理的风控、计算完结类:

public class SellDynamicProxy {
    /**
     * 获取传入方针方针的署理方针
     * @param target
     * @return
     */
    public Object createProxy(Object target) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(), //方针方针运用类加载器
                target.getClass().getInterfaces(),  //方针方针完结的接口的类型
                new DynamicProxyHandler(target));   //方针方针事情处理器
    }
    /**
     * 方针方针的事情处理器
     */
    private class DynamicProxyHandler implements InvocationHandler {
        //被署理方针
        private Object target;
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("JD售前风控。。。");
            method.invoke(target, args);
            System.out.println("JD售后计算。。。");
            return null;
        }
        public DynamicProxyHandler(Object object) {
            this.target = object;
        }
    }
}

测验:

public class MainClass {
    public static void main(String[] args) {
        //创立动态署理渠道
        SellDynamicProxy dynamicProxy = new SellDynamicProxy();
        //署理出售机票
        SellAirTicket airTicketProxy = (SellAirTicket) dynamicProxy.createProxy(new SellAirTicketImpl());
        airTicketProxy.sellAirTicket(600);
        //署理出售稳妥
        SellInsurance insuranceProxy = (SellInsurance) dynamicProxy.createProxy(new SellInsuranceImpl());
        insuranceProxy.sellInsurance(30);
    }
}

测验成果:

JD售前风控。。。
航司出售机票,价格:600
JD售后计算。。。
JD售前风控。。。
稳妥公司出售稳妥,价格:30
JD售后计算。。。

进阶的一对多协作办法,动态署理

到这儿航司、稳妥公司都找到了自己的署理,JD渠道也完结了风控、计算署理渠道的搭建。再有人来找自己,JD渠道都能够满意署理需求,现在看来,已经很完美了。

被署理的商家与JD归于动态绑定的联系,即:被署理类与署理类归于动态绑定的联系,称之为“动态署理”,因为此署理功能依赖JDK供给的Proxy、InvocationHandler类,也成为“JDK动态署理”。

据此,咱们能够弥补署理形式的界说:

【署理形式】 便是在不改动原有类(被署理类)的情况下,为原有类创立署理方针,对原有类的功能做增强的一种形式
署理形式的优点:
1. 满意单一准则,事务类能够只关怀自己的中心逻辑,非中心逻辑由署理类完结;
2. 易于保护,中心逻辑、非中心逻辑的修正不会相互影响;
3. 关于用户(调用者)而言,运用的办法没有差异,能够做到低成本替换;
4. JDK动态署理能够动态的绑定方针类,能够减少代码量,进步代码的复用;
署理形式的缺陷:
1. 静态署理每个被署理类都要有一个署理类,大大增加了代码量;
2. JDK动态署理根据JDK的反射原理完结,降低了履行功率;  

酒店呈现,署理公司意外来临

平静的日子没过多久,一天某酒店找来了,要求给他们做署理,做就做呗。轻车又熟路。。。

酒店出售房间:

public class SellHotel {
    /**
     * 出售酒店
     * @param price
     */
    public void sellHotel(int price) {
        System.out.println("酒店出售房间,价格:" + price);
    }
}  

测验:

public class MainClass {
    public static void main(String[] args) {
        //创立动态署理渠道
        SellDynamicProxy dynamicProxy = new SellDynamicProxy();
        //署理出售酒店
        SellHotel sellHotel = (SellHotel) dynamicProxy.createProxy(new SellHotel());
        sellHotel.sellHotel(300);
    }
}  

测验成果:

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be
cast to demo.pattern.proxy.SellHotel at demo.pattern.proxy.MainClass.main(MainClass.java:14)

怎么回事,渠道不好用了!署理公司闭关修炼,查一下问题。。。

优秀署理公司的自我修养

以前给他人署理都好使,这次给酒店署理为何就不行了呢? 一个优秀的署理,有问题就要处理问题。。。

先看反常,署理类不能被强转为方针类型,但是为何之前的都好使?

考虑:只要生成的署理类归于方针类型,才干强转,那就需求署理类完结方针类的接口,那问题就可能是这样了,验证一下。

原理剖析:JDK署理方针是怎么完结的?

让咱们先看下源码

/**
 * 获取传入方针方针的署理方针
 * @param target
 * @return
 */
public Object createProxy(Object target) {
    return Proxy.newProxyInstance(
            target.getClass().getClassLoader(), //方针方针运用类加载器
            target.getClass().getInterfaces(),  //方针方针完结的接口的类型
            new DynamicProxyHandler(target));   //方针方针事情处理器
}
/**
 * 创立署理类源码
 */
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);
    }
}
/**
 * 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);     //这儿获取字节码方针
}
/**
 * 这儿获取字节码方针
 */
public V get(K key, P parameter) {
    Objects.requireNonNull(parameter);
    expungeStaleEntries();
    Object cacheKey = CacheKey.valueOf(key, refQueue);
    // lazily install the 2nd level valuesMap for the particular cacheKey
    ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
    if (valuesMap == null) {
        ConcurrentMap<Object, Supplier<V>> oldValuesMap
            = map.putIfAbsent(cacheKey,
                              valuesMap = new ConcurrentHashMap<>());
        if (oldValuesMap != null) {
            valuesMap = oldValuesMap;
        }
    }
    // create subKey and retrieve the possible Supplier<V> stored by that
    // subKey from valuesMap
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));    //这儿创立字解码方针
    Supplier<V> supplier = valuesMap.get(subKey);
    Factory factory = null;
    while (true) {
        if (supplier != null) {
            // supplier might be a Factory or a CacheValue<V> instance
            V value = supplier.get();
            if (value != null) {
                return value;
            }
        }
        // else no supplier in cache
        // or a supplier that returned null (could be a cleared CacheValue
        // or a Factory that wasn't successful in installing the CacheValue)
        // lazily construct a Factory
        if (factory == null) {
            factory = new Factory(key, parameter, subKey, valuesMap);
        }
        if (supplier == null) {
            supplier = valuesMap.putIfAbsent(subKey, factory);
            if (supplier == null) {
                // successfully installed Factory
                supplier = factory;
            }
            // else retry with winning supplier
        } else {
            if (valuesMap.replace(subKey, supplier, factory)) {
                // successfully replaced
                // cleared CacheEntry / unsuccessful Factory
                // with our Factory
                supplier = factory;
            } else {
                // retry with current supplier
                supplier = valuesMap.get(subKey);
            }
        }
    }
}
/**
 * A factory function that generates, defines and returns the proxy class given
 * the ClassLoader and array of interfaces.
 * 
 * Proxy类的内部类,便是为了创立署理方针的字节码方针
 */
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());
        }
    }
}

上面剖析一堆,那咱们来了看看得到的署理类到底是啥,为啥他就能履行那个咱们的方针类的办法。一起,还得方针类完结接口?

/**
 * 咱们自己生成一份方针类字节码文件
 * @throws IOException
 */
public static void transClass() throws IOException {
    SellAirTicketImpl sellAirTicket = new SellAirTicketImpl();
    byte[] bts = ProxyGenerator.generateProxyClass("$Proxy0", sellAirTicket.getClass().getInterfaces());
    File file = new File("E:\test","$Proxy0.class");
    if (!file.exists()){
        file.createNewFile();
    }
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(bts);
    fos.flush();
    fos.close();
}

将咱们的字节码文件在此反编译:**javare.cn**,得到咱们的署理类:

import demo.pattern.proxy.SellAirTicket;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy0 extends Proxy implements SellAirTicket {
   private static Method m1;
   private static Method m2;
   private static Method m3;
   private static Method m0;
   public $Proxy0(InvocationHandler var1) throws  {     //署理类的结构器,将事情处理器传入,交给父类Proxy
      super(var1);
   }
   public final boolean equals(Object var1) throws  {
      try {
         return ((Boolean)super.h.invoke(this, m1, new Object[]{var1})).booleanValue();
      } catch (RuntimeException | Error var3) {
         throw var3;
      } catch (Throwable var4) {
         throw new UndeclaredThrowableException(var4);
      }
   }
   public final String toString() throws  {
      try {
         return (String)super.h.invoke(this, m2, (Object[])null);
      } catch (RuntimeException | Error var2) {
         throw var2;
      } catch (Throwable var3) {
         throw new UndeclaredThrowableException(var3);
      }
   }
   public final void sellAirTicket(int var1) throws  {
      try {
         super.h.invoke(this, m3, new Object[]{Integer.valueOf(var1)});     //履行方针办法时,调用父类的事情处理器
      } catch (RuntimeException | Error var3) {
         throw var3;
      } catch (Throwable var4) {
         throw new UndeclaredThrowableException(var4);
      }
   }
   public final int hashCode() throws  {
      try {
         return ((Integer)super.h.invoke(this, m0, (Object[])null)).intValue();
      } catch (RuntimeException | Error var2) {
         throw var2;
      } catch (Throwable var3) {
         throw new UndeclaredThrowableException(var3);
      }
   }
   static {
      try {
         m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]{Class.forName("java.lang.Object")});
         m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
         m3 = Class.forName("demo.pattern.proxy.SellAirTicket").getMethod("sellAirTicket", new Class[]{Integer.TYPE});  //获取接口类型的方针办法
         m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
      } catch (NoSuchMethodException var2) {
         throw new NoSuchMethodError(var2.getMessage());
      } catch (ClassNotFoundException var3) {
         throw new NoClassDefFoundError(var3.getMessage());
      }
   }
}

到此为止真相大白了,原来署理类承继了Proxy父类,一起完结了方针类的接口,这就将咱们的方针办法与界说的事情处理器联系起来了。

一起,因为java的单承继形式,导致了署理类只能承继Proxy类,那这样的话,就只好通过方针类的接口来相关方针类了。

小结:JDK动态署理

据此,咱们能够再次弥补署理形式的界说:

【署理形式】 便是在不改动原有类(被署理类)的情况下,为原有类创立署理方针,对原有类的功能做增强的一种形式
署理形式的优点:
1. 满意单一准则,事务类能够只关怀自己的中心逻辑,非中心逻辑由署理类完结;
2. 易于保护,中心逻辑、非中心逻辑的修正不会相互影响;
3. 关于用户(调用者)而言,运用的办法没有差异,能够做到低成本替换;
4. JDK动态署理能够动态的绑定方针类,能够减少代码量,进步代码的复用;
署理形式的缺陷:
1. 静态署理每个被署理类都要有一个署理类,大大增加了代码量;
2. JDK动态署理根据JDK的反射原理完结,降低了履行功率;  
3. JDK动态署理是根据接口的署理,要求方针类必须完结方针接口;

好的协作伙伴便是不扔掉不抛弃

到这儿,问题是搞明白了,便是酒店的问题,但是好的协作伙伴便是应该不扔掉,不抛弃。

酒店跟咱们协作,咱们就要协助他们处理困难。那怎么办呢?酒店没接口,JDK署理又非要接口,那咱们就不必JDK署理了!

这时,根据类的署理办法就应运而生了—— cglib为咱们供给了根据类的动态署理形式。

导Jar包:cglib-3.2.5.jar(cglib中心包)、asm-3.3.1.jar(字节码处理框架

public class CglibDynamicProxy implements MethodInterceptor {
    //方针方针
    private Object target;
    /**
     *给方针方针创立一个署理方针
     */
    public Object getProxyInstance(){
        //工具类
        Enhancer en = new Enhancer();
        //设置父类
        en.setSuperclass(target.getClass());
        //设置回调函数
        en.setCallback(this);
        //创立子类署理方针
        return en.create();
    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib售前风控。。。");
        final Object invoke = method.invoke(target, objects);
        System.out.println("cglib售后计算。。。");
        return invoke;
    }
    public CglibDynamicProxy(Object target) {
        this.target = target;
    }
}

测验

    public static void main(String[] args) {
        //创立出售酒店署理
        CglibDynamicProxy cglibDynamicProxy = new CglibDynamicProxy(new SellHotel());
        SellHotel sellHotel = (SellHotel) cglibDynamicProxy.getProxyInstance();
        sellHotel.sellHotel(300);
    }

测验成果

    cglib售前风控。。。
    酒店出售房间,价格:300
    cglib售后计算。。。

原理剖析:cglib署理方针是怎么完结的?

那为啥cglib就不必方针类完结接口了呢?让咱们看看署理类。

public static void main(String[] args) {
    //署理类class文件存入本地磁盘
    System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "E:\testCglib");
    //创立出售酒店署理
    CglibDynamicProxy cglibDynamicProxy = new CglibDynamicProxy(new SellHotel());
    SellHotel sellHotel = (SellHotel) cglibDynamicProxy.getProxyInstance();
    sellHotel.sellHotel(300);
}

反编译成果

/**
 * 署理类反编译成果
 */
public class SellHotel$$EnhancerByCGLIB$$2624d6e3 extends SellHotel implements Factory {
   private boolean CGLIB$BOUND;
   public static Object CGLIB$FACTORY_DATA;
   private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
   private static final Callback[] CGLIB$STATIC_CALLBACKS;
   private MethodInterceptor CGLIB$CALLBACK_0;      //办法拦截器
   private static final Method CGLIB$sellHotel$0$Method;    //被署理办法
   private static final MethodProxy CGLIB$sellHotel$0$Proxy;    //署理办法
   private static final Object[] CGLIB$emptyArgs;
   private static final Method CGLIB$equals$1$Method;
   private static final MethodProxy CGLIB$equals$1$Proxy;
   private static final Method CGLIB$toString$2$Method;
   private static final MethodProxy CGLIB$toString$2$Proxy;
   private static final Method CGLIB$hashCode$3$Method;
   private static final MethodProxy CGLIB$hashCode$3$Proxy;
   private static final Method CGLIB$clone$4$Method;
   private static final MethodProxy CGLIB$clone$4$Proxy;
   static void CGLIB$STATICHOOK1() {
      CGLIB$THREAD_CALLBACKS = new ThreadLocal();
      CGLIB$emptyArgs = new Object[0];
      Class var0 = Class.forName("demo.pattern.proxy.SellHotel$$EnhancerByCGLIB$$2624d6e3");    //署理类
      Class var1;   //被署理类
      CGLIB$sellHotel$0$Method = ReflectUtils.findMethods(new String[]{"sellHotel", "(I)V"}, (var1 = Class.forName("demo.pattern.proxy.SellHotel")).getDeclaredMethods())[0];
      CGLIB$sellHotel$0$Proxy = MethodProxy.create(var1, var0, "(I)V", "sellHotel", "CGLIB$sellHotel$0");
      Method[] var10000 = ReflectUtils.findMethods(new String[]{"equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
      CGLIB$equals$1$Method = var10000[0];
      CGLIB$equals$1$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$1");
      CGLIB$toString$2$Method = var10000[1];
      CGLIB$toString$2$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$2");
      CGLIB$hashCode$3$Method = var10000[2];
      CGLIB$hashCode$3$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$3");
      CGLIB$clone$4$Method = var10000[3];
      CGLIB$clone$4$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$4");
   }
   final void CGLIB$sellHotel$0(int var1) {
      super.sellHotel(var1);
   }
   public final void sellHotel(int var1) {  //署理类重写的办法
      MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;       //办法拦截器
      if(this.CGLIB$CALLBACK_0 == null) {
         CGLIB$BIND_CALLBACKS(this);
         var10000 = this.CGLIB$CALLBACK_0;
      }
      if(var10000 != null) {    //履行办法拦截器
         var10000.intercept(this, CGLIB$sellHotel$0$Method, new Object[]{new Integer(var1)}, CGLIB$sellHotel$0$Proxy);
      } else {
         super.sellHotel(var1);
      }
   }
   final boolean CGLIB$equals$1(Object var1) {
      return super.equals(var1);
   }
   public final boolean equals(Object var1) {
      MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
      if(this.CGLIB$CALLBACK_0 == null) {
         CGLIB$BIND_CALLBACKS(this);
         var10000 = this.CGLIB$CALLBACK_0;
      }
      if(var10000 != null) {
         Object var2 = var10000.intercept(this, CGLIB$equals$1$Method, new Object[]{var1}, CGLIB$equals$1$Proxy);
         return var2 == null?false:((Boolean)var2).booleanValue();
      } else {
         return super.equals(var1);
      }
   }
   final String CGLIB$toString$2() {
      return super.toString();
   }
   public final String toString() {
      MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
      if(this.CGLIB$CALLBACK_0 == null) {
         CGLIB$BIND_CALLBACKS(this);
         var10000 = this.CGLIB$CALLBACK_0;
      }
      return var10000 != null?(String)var10000.intercept(this, CGLIB$toString$2$Method, CGLIB$emptyArgs, CGLIB$toString$2$Proxy):super.toString();
   }
   final int CGLIB$hashCode$3() {
      return super.hashCode();
   }
   public final int hashCode() {
      MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
      if(this.CGLIB$CALLBACK_0 == null) {
         CGLIB$BIND_CALLBACKS(this);
         var10000 = this.CGLIB$CALLBACK_0;
      }
      if(var10000 != null) {
         Object var1 = var10000.intercept(this, CGLIB$hashCode$3$Method, CGLIB$emptyArgs, CGLIB$hashCode$3$Proxy);
         return var1 == null?0:((Number)var1).intValue();
      } else {
         return super.hashCode();
      }
   }
   final Object CGLIB$clone$4() throws CloneNotSupportedException {
      return super.clone();
   }
   protected final Object clone() throws CloneNotSupportedException {
      MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
      if(this.CGLIB$CALLBACK_0 == null) {
         CGLIB$BIND_CALLBACKS(this);
         var10000 = this.CGLIB$CALLBACK_0;
      }
      return var10000 != null?var10000.intercept(this, CGLIB$clone$4$Method, CGLIB$emptyArgs, CGLIB$clone$4$Proxy):super.clone();
   }
   public static MethodProxy CGLIB$findMethodProxy(Signature var0) {
      String var10000 = var0.toString();
      switch(var10000.hashCode()) {
      case -508378822:
         if(var10000.equals("clone()Ljava/lang/Object;")) {
            return CGLIB$clone$4$Proxy;
         }
         break;
      case 1826985398:
         if(var10000.equals("equals(Ljava/lang/Object;)Z")) {
            return CGLIB$equals$1$Proxy;
         }
         break;
      case 1913648695:
         if(var10000.equals("toString()Ljava/lang/String;")) {
            return CGLIB$toString$2$Proxy;
         }
         break;
      case 1979480752:
         if(var10000.equals("sellHotel(I)V")) {
            return CGLIB$sellHotel$0$Proxy;
         }
         break;
      case 1984935277:
         if(var10000.equals("hashCode()I")) {
            return CGLIB$hashCode$3$Proxy;
         }
      }
      return null;
   }
   public SellHotel$$EnhancerByCGLIB$$2624d6e3() {
      CGLIB$BIND_CALLBACKS(this);
   }
   public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] var0) {
      CGLIB$THREAD_CALLBACKS.set(var0);
   }
   public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] var0) {
      CGLIB$STATIC_CALLBACKS = var0;
   }
   private static final void CGLIB$BIND_CALLBACKS(Object var0) {
      SellHotel$$EnhancerByCGLIB$$2624d6e3 var1 = (SellHotel$$EnhancerByCGLIB$$2624d6e3)var0;
      if(!var1.CGLIB$BOUND) {
         var1.CGLIB$BOUND = true;
         Object var10000 = CGLIB$THREAD_CALLBACKS.get();
         if(var10000 == null) {
            var10000 = CGLIB$STATIC_CALLBACKS;
            if(CGLIB$STATIC_CALLBACKS == null) {
               return;
            }
         }
         var1.CGLIB$CALLBACK_0 = (MethodInterceptor)((Callback[])var10000)[0];
      }
   }
   public Object newInstance(Callback[] var1) {
      CGLIB$SET_THREAD_CALLBACKS(var1);
      SellHotel$$EnhancerByCGLIB$$2624d6e3 var10000 = new SellHotel$$EnhancerByCGLIB$$2624d6e3();
      CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
      return var10000;
   }
   public Object newInstance(Callback var1) {
      CGLIB$SET_THREAD_CALLBACKS(new Callback[]{var1});
      SellHotel$$EnhancerByCGLIB$$2624d6e3 var10000 = new SellHotel$$EnhancerByCGLIB$$2624d6e3();
      CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
      return var10000;
   }
   public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
      CGLIB$SET_THREAD_CALLBACKS(var3);
      SellHotel$$EnhancerByCGLIB$$2624d6e3 var10000 = new SellHotel$$EnhancerByCGLIB$$2624d6e3;
      switch(var1.length) {
      case 0:
         var10000.<init>();
         CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
         return var10000;
      default:
         throw new IllegalArgumentException("Constructor not found");
      }
   }
   public Callback getCallback(int var1) {
      CGLIB$BIND_CALLBACKS(this);
      MethodInterceptor var10000;
      switch(var1) {
      case 0:
         var10000 = this.CGLIB$CALLBACK_0;
         break;
      default:
         var10000 = null;
      }
      return var10000;
   }
   public void setCallback(int var1, Callback var2) {
      switch(var1) {
      case 0:
         this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
      default:
      }
   }
   public Callback[] getCallbacks() {
      CGLIB$BIND_CALLBACKS(this);
      return new Callback[]{this.CGLIB$CALLBACK_0};
   }
   public void setCallbacks(Callback[] var1) {
      this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
   }
   static {
      CGLIB$STATICHOOK1();
   }
}

到此,咱们知道cglib署理是帮咱们新建了一个署理类,此署理类承继自方针类获取方针办法,一起重写了方针办法。

再通过咱们界说的拦截器调用咱们的方针办法,以此来到达署理方针办法的意图。

总结:JDK、cglib动态署理

据此,咱们能够总结署理形式的界说:

【署理形式】 便是在不改动原有类(被署理类)的情况下,为原有类创立署理方针,对原有类的功能做增强的一种形式。
署理形式的优点:
1. 满意单一准则,事务类能够只关怀自己的中心逻辑,非中心逻辑由署理类完结;
2. 易于保护,中心逻辑、非中心逻辑的修正不会相互影响;
3. 关于用户(调用者)而言,运用的办法没有差异,能够做到低成本替换;
4. JDK动态署理能够动态的绑定方针类,能够减少代码量,进步代码的复用;
5. cglib动态署理可根据完结类做署理,能够处理JDK署理依赖接口的问题;
署理形式的缺陷:
1. 静态署理每个被署理类都要有一个署理类,大大增加了代码量;
2. JDK动态署理根据JDK的反射原理完结,降低了履行功率;  
3. JDK动态署理是根据接口的署理,要求方针类必须完结方针接口;
署理形式分类:
1. 静态署理;
2. JDK动态署理(根据方针类的接口生成署理类做署理);
3. cglib动态署理(根据方针类生成子类做署理,一起也支持根据接口的署理);

署理形式的运用场景

咱们知道,Spring的AOP便是依赖于动态署理形式完结的,那咱们在日常的开发中有哪些地方能用到署理呢?

•事物

•日志

•监控

•计算

•鉴权

•限流

•缓存

环境阻隔