0%

代理模式

在研究Spring以及Mybatis源码时,看到很多地方用到了设计模式;

代理模式有静态代理,动态代理之分,动态代理里面又有JDK动态代理,Cglib动态代理两种;

代理模式在源码中经常看到,特地总结写,强化自己的理解,希望23种设计模式陆陆续续都总结一下;

柯南是不是也有点新一的代理的意思呢?

网络图片

定义

代理模式的定义:代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用;

代理模式理解:代理类,被代理类 都实现代理接口,代理类持有被代理类,当被代理类的接口方法需要被执行时,由代理类带为执行;

作用: 通过代理类来隔绝client直接访问代理类;

网络图片

通过Uml图来理解:对于JDK的代理模式,不管是静态代理还是动态代理,Client想调用被代理类的方法,都是代理类代为执行。关键都在代理类上;

JDK代理模式

JDK的代理模式,要求代理类,被代理类都实现公共的接口方法;

接口:

1
2
3
4
5
6
public interface Method{

String method(String str);

}

静态代理

最简单的代理实现:纯手撸,可能有打错的,静态代理比较简单不是总结的关键;

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
34
//被代理类
public class RealMethodImpl implements Method{

String method(String str){
System.out.println(str);
return "method"+ str;
}

}

//代理类
public class ProxyMethodImpl implements Method{
Method realMethod ;

public ProxyMethodImpl(Method realMethod){
this.realMethod = realMethod;
}

String method(String str){
return realMethod.method(str);
}

}

// 调用端
public class Client {

public static void main(String[] args){
Method proxy = new ProxyMethodImpl(new RealMethodImpl())
proxy.method("执行");
}

}

动态代理

静态代理虽然使用方便,理解也很简单,但是应对不同的需求可能需要频频修改代理类,或者创建代理类;

相比于静态代理的这种问题,动态代理就显得更加有优势,动态代理不需要手动定义代理类,而是由系统创建在内存中;

动态代理只需要关注InvocationHandler的实现类;

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
34
35
36
37
38
39
public class Client {

public static void main(String[] args){

InvocationHandler invocationHandler = new ProxyInvocationHandler(new RealMethodImpl());

// userServiceProxy 是生成的代理类;也就是invocationHandler 中invoke 方法中的proxy;
Method userServiceProxy = (Method)Proxy.newProxyInstance(invocationHandler.getClass().getClassLoader(),
new Class[]{Method.class}, invocationHandler);

userServiceProxy.method("userServiceProxy.method");
}


//InvocationHandler 实现类
public class ProxyInvocationHandler implements InvocationHandler{
Method realMethod ;

public ProxyInvocationHandler(Method realMethod){
this.realMethod = realMethod;
}

/**
* proxy : 这个就是系统生成的 代理类 也就是ProxyInvocationHandler 的实例;
* method : 接口当前被调用的的方法
* args : 方法闯入的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("执行前");
// 这里调用realMethod的method; 注意!!! 这个传入的是 真正的被代理类!
Object result = method.invoke(realMethod, args);
System.out.println("执行后");
return result;
}
}

}

动态代理源码跟踪

了解完JDK动态代理使用之后,来大致的了解下源码实现是什么样子的:

Proxy

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
34
35
36
37
38
39
40
41
42
43
44
这里我摘取出关键的代码:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{

final Class<?>[] intfs = interfaces.clone();

/*
* Look up or generate the designated proxy class.
*/
// 根据接口 获取代理类class
Class<?> cl = getProxyClass0(loader, intfs);

/*
* Invoke its constructor with the designated invocation handler.
*/
try {

// 获取构造
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;

}
// 通过构造创建代理类实例
return cons.newInstance(new Object[]{h});
} catch (Exception e) {
throw new InternalError(e.toString(), e);
}
}

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);
}

WeakCache

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Look-up the value through the cache. This always evaluates the
* {@code subKeyFactory} function and optionally evaluates
* {@code valueFactory} function if there is no entry in the cache for given
* pair of (key, subKey) or the entry has already been cleared.
*/
public V get(K key, P parameter) {
Object cacheKey = CacheKey.valueOf(key, refQueue);

// lazily install the 2nd level valuesMap for the particular cacheKey
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);

// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap 从valuesMap 中获取subKey
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));

// 更加subKey 获取 supplier factory 最终返回class
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);
}
}
}
}

Proxy#ProxyClassFactory 最终调用native 方法 defineClass0 获取class

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* 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 {
// native 方法
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());
}
}
}

Cglib动态代理

JDK 的动态代理存在一定的限制:被代理类必须实现接口。Cglib就没有这个限制,被代理类可以是没有实现接口的普通类;

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
34

public class CglibMethodInterceptor implements MethodInterceptor{

/**
* sub:cglib生成的代理对象
* method:被代理对象方法
* objects:方法入参
* methodProxy: 代理方法
*/
@Override
public Object intercept(Object sub, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("执行前");
Object object = methodProxy.invokeSuper(sub, objects);
System.out.println("执行后");
return object;
}
}

public class Client {

public static void main(String[] args){

// 通过CGLIB动态代理获取代理对象的过程
Enhancer enhancer = new Enhancer();
// 设置enhancer对象的父类
enhancer.setSuperclass(Pojo.class);
// 设置enhancer的回调对象
enhancer.setCallback(new CglibMethodInterceptor());
// 创建代理对象
Pojo proxy= (Pojo)enhancer.create();
// 通过代理对象调用目标方法
proxy.sayHello();
}

GitHub登录不了?信任该网站之后再登录。