一、代理模式定义
给某个对象提供一个代理对象,并由代理对象控制对于原对象的访问,即客户不直接操控原对象,而是通过代理对象间接地操控原对象。
著名的代理模式的例子就是引用计数(reference counting): 当需要一个复杂对象的多份副本时, 代理模式可以结合享元模式以减少存储器的用量。典型做法是创建一个复杂对象以及多个代理者, 每个代理者会引用到原本的对象。而作用在代理者的运算会转送到原本对象。一旦所有的代理者都不存在时, 复杂对象会被移除。
要理解代理模式很简单,其实生活当中就存在代理模式:
我们购买火车票可以去火车站买,但是也可以去火车票代售处买,此处的火车票代售处就是火车站购票的代理,即我们在代售点发出买票请求,代售点会把请求发给火车站,火车站把购买成功响应发给代售点,代售点再告诉你。
但是代售点只能买票,不能退票,而火车站能买票也能退票,因此代理对象支持的操作可能和委托对象的操作有所不同。
再举一个写程序会碰到的一个例子:
如果现在有一个已有项目(你没有源代码,只能调用它)能够调用 int compute(string exp1) 实现对于后缀表达式的计算,你想使用这个项目实现对于中缀表达式的计算,那么你可以写一个代理类,并且其中也定义一个compute(string exp2),这个exp2参数是中缀表达式,因此你需要在调用已有项目的 compute() 之前将中缀表达式转换成后缀表达式(preprocess),再调用已有项目的compute(),当然你还可以接收到返回值之后再做些其他操作比如存入文件(postprocess),这个过程就是使用了代理模式。
在平时用电脑也会碰到代理模式的应用:
远程代理:我们在国内因为gfw,所以不能访问 facebook,我们可以用翻墙(设置代理)的方法访问。访问过程是:
(1)用户把http请求发给代理
(2)代理把http请求发给web服务器
(3)web服务器把http响应发给代理
(4)代理把http响应发回给用户
二、静态代理
所谓静态代理, 就是在编译阶段就生成代理类来完成对代理对象的一系列操作。下面是代理模式的结构类图:
1、代理模式的参与者
代理模式的角色分四种:
主题接口: 即代理类的所实现的行为接口。
目标对象: 也就是被代理的对象。
代理对象: 用来封装真是主题类的代理类
客户端
下面是代理模式的类图结构:
2、代理模式的实现思路
代理对象和目标对象均实现同一个行为接口。
代理类和目标类分别具体实现接口逻辑。
在代理类的构造函数中实例化一个目标对象。
在代理类中调用目标对象的行为接口。
客户端想要调用目标对象的行为接口,只能通过代理类来操作。
3、静态代理的实例
下面以一个延迟加载的例子来说明一下静态代理。我们在启动某个服务系统时, 加载某一个类时可能会耗费很长时间。为了获取更好的性能, 在启动系统的时候, 我们往往不去初始化这个复杂的类, 取而代之的是去初始化其代理类。这样将耗费资源多的方法使用代理进行分离, 可以加快系统的启动速度, 减少用户等待的时间。
定义一个主题接口
public interface subject {
public void sayhello();
public void saygoodbye();
}
定义一个目标类, 并实现主题接口
public class realsubject implements subject {
public void sayhello() {
system.out.println("hello world");
}
public void saygoodbye() {
system.out.println("goodbye world");
}
}
定义一个代理类, 来代理目标对象。
public class staticproxy implements subject {
private realsubject realsubject = null;
public staticproxy() {}
public void sayhello() {
//用到时候才加载, 懒加载
if(realsubject == null) {
realsubject = new realsubject();
}
realsubject.sayhello();
}
//saygoodbye方法同理
...
}
定义一个客户端
public class client {
public static void main(string [] args) {
staticproxy sp = new staticproxy();
sp.sayhello();
sp.saygoodbye();
}
}
以上就是静态代理的一个简单测试例子。感觉可能没有实际用途。然而并非如此。使用代理我们还可以将目标对象的方法进行改造, 比如数据库连接池中创建了一系列连接, 为了保证不频繁的打开连接,这些连接是几乎不会关闭的。然而我们编程总有习惯去将打开的connection去close。 这样我们就可以利用代理模式来重新代理connection接口中的close方法, 改变为回收到数据库连接池中而不是真正的执行connection#close方法。其他的例子还有很多, 具体需要自己体会。
三、动态代理
动态代理是指在运行时动态生成代理类。即,代理类的字节码将在运行时生成并载入当前代理的 classloader。与静态处理类相比,动态类有诸多好处。
不需要为真实主题写一个形式上完全一样的封装类,假如主题接口中的方法很多,为每一个接口写一个代理方法也很麻烦。如果接口有变动,则真实主题和代理类都要修改,不利于系统维护;
使用一些动态代理的生成方法甚至可以在运行时制定代理类的执行逻辑,从而大大提升系统的灵活性。
生成动态代理的方法有很多: jdk中自带动态代理, cglib, javassist等。这些方法各有优缺点。本文主要探究jdk中的动态代理的使用和源码分析。
下面用一个实例讲解一下jdk中动态代理的用法:
public class dynamicproxy implements invocationhandler {
private realsubject = null;
public object invoke(object proxy, method method, object[] args){
if(realsubject == null) {
realsubject = new realsubject();
}
method.invoke(realsubject, args);
return realsubject;
}
}
客户端代码实例
public class client {
public static void main(strings[] args) {
subject subject = (subject)proxy.newinstance(classloader.getsystemloader(), realsubject.class.getinterfaces(), new dynamicproxy());
subject.sayhello();
subject.saygoodbye();
}
}
从上面的代码可以看出, 要利用jdk中的动态代理。利用静态方法proxy.newinstance(classloader, interfaces[], invokehandler)可以创建一个动态代理类。 newinstance方法有三个参数, 分别表示类加载器, 一个希望该代理类实现的接口列表, 以及实现invokehandler接口的实例。 动态代理将每个方法的执行过程则交给了invoke方法处理。
jdk动态代理要求, 被代理的必须是个接口, 单纯的类则不行。jdk动态代理所生成的代理类都会继承proxy类,同时代理类会实现所有你传入的接口列表。因此可以强制类型转换成接口类型。 下面是proxy的结构图。
可以看出proxy全是静态方法, 因此如果代理类没有实现任何接口, 那么他就是proxy类型, 没有实例方法。
当然加入你要是非要代理一个没有实现某个接口的类, 同时该类的方法与其他接口定义的方法相同, 利用反射也是可以轻松实现的。
public class dynamicproxy implements invokehandler {
//你想代理的类
private targetclass targetclass = null;
//初始化该类
public dynamicproxy(targetclass targetclass) {
this.targetclass = targetclass;
}
public object invoke(object proxy, method method, object[] args) {
//利用反射获取你想代理的类的方法
method mymethod = targetclass.getclass().getdeclaredmethod(method.getname(), method.getparametertypes());
mymethod.setaccessible(true);
return mymethod.invoke(targetclass, args);
}
}
四、jdk动态代理源码分析(jdk7)
看了上面的例子, 我们只是简单会用动态代理。但是对于代理类是如何创建出来的, 是谁调用invoke方法等还云里雾里。下面通过分析
1、代理对象是如何创建出来的?
首先看proxy.newinstance方法的源码:
public static object newproxyinstance(classloader loader, class<?>[] interfaces, invocationhandler h) throws illegalargumentexception {
}
//获取接口信息
final class<?>[] intfs = interfaces.clone();
final securitymanager sm = system.getsecuritymanager();
if (sm != null) {
checkproxyaccess(reflection.getcallerclass(), loader, intfs);
}
//生成代理类
class<?> cl = getproxyclass0(loader, intfs);
// ...ok我们先看前半截
}
从源码看出代理类的生成是依靠getproxyclass0这个方法, 接下来看getproxyclass0源码:
private static class<?> getproxyclass0(classloader loader, class<?>... interfaces) {
//接口列表数目不能超过0xffff
if (interfaces.length > 65535) {
throw new illegalargumentexception("interface limit exceeded");
}
//注意这里, 下面详细解释
return proxyclasscache.get(loader, interfaces);
}
对proxyclasscache.get的解释是: 如果实现接口列表的代理类已经存在,那么直接从cache中拿。如果不存在, 则通过proxyclassfactory生成一个。
在看proxyclasscache.get源码之前,先简单了解一下proxyclasscache:
private static final weakcache<classloader, class<?>[], class<?>>
proxyclasscache = new weakcache<>(new keyfactory(), new proxyclassfactory());
proxyclasscache是一个weakcache类型的缓存, 它的构造函数有两个参数, 其中一个就是用于生成代理类的proxyclassfactory, 下面是proxyclasscache.get的源码:
final class weakcache<k, p, v> {
...
public v get(k key, p parameter) {}
}
这里k表示key, p表示parameters, v表示value
public v get(k key, p parameter) {
//java7 nullobject判断方法, 如果parameter为空则抛出带有指定消息的异常。 如果不为空则返回。
objects.requirenonnull(parameter);
//清理持有弱引用的weakhashmap这种数据结构,一般用于缓存
expungestaleentries();
//从队列中获取cachekey
object cachekey = cachekey.valueof(key, refqueue);
//利用懒加载的方式填充supplier, concurrent是一种线程安全的map
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中获取value,这个value可能是一个工厂或者cache的实
//下面这三句代码是核心代码, 返回实现invokehandler的类并包含了所需要的信息。
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)
//下面这个过程就是填充supplier的过程
if(factory == null) {
//创建一个factory
}
if(supplier == null) {
//填充supplier
}else {
//填充supplier
}
}
while循环的作用就是不停的获取实现invokehandler的类, 这个类可以是从缓存中拿到,也可是是从proxyfactoryclass生成的。
factory是一个实现了supplier<v>接口的内部类。这个类覆盖了get方法, 在get方法中调用了类型为proxyfactoryclass的实例方法apply。这个方法才是真正创建代理类的方法。下面看proxyfactoryclass#apply方法的源码:
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) {
}
//如果使用你自己的classload加载的class与你传入的class不相等,抛出异常
if (interfaceclass != intf) {
throw new illegalargumentexception(
intf + " is not visible from class loader");
}
//如果传入不是一个接口类型
if (!interfaceclass.isinterface()) {
throw new illegalargumentexception(
interfaceclass.getname() + " is not an interface");
}
//验证接口是否重复
if (interfaceset.put(interfaceclass, boolean.true) != null) {
throw new illegalargumentexception("repeated interface: " + interfaceclass.getname());
}
}
string proxypkg = null; // package to define proxy class in
/* 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.
*/
//这一段是看你传入的接口中有没有不是public的接口,如果有,这些接口必须全部在一个包里定义的,否则抛异常
for (class<?> intf : interfaces) {
int flags = intf.getmodifiers();
if (!modifier.ispublic(flags)) {
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();
//生成随机代理类的类名, $proxy + num
string proxyname = proxypkg + proxyclassnameprefix + num;
/*
* 生成代理类的class文件, 返回字节流
*/
byte[] proxyclassfile = proxygenerator.generateproxyclass(proxyname, interfaces);
try {
return defineclass0(loader, proxyname, proxyclassfile, 0, proxyclassfile.length);
} catch (classformaterror e) {
//结束
throw new illegalargumentexception(e.tostring());
}
}
}
前文提到proxyfactoryclass#apply是真正生成代理类的方法, 这其实是不准确的。源代码读到这里,我们会发现proxygenerator#generateproxyclass才是真正生成代理类的方法。根据java class字节码组成(可以参见我的另一篇文章java字节码学习笔记)来生成相应的clss文件。具体proxygenerator#generateproxyclass源码如下:
private byte[] generateclassfile() {
/*
* step 1: assemble proxymethod objects for all methods to
* generate proxy dispatching code for.
*/
//addproxymethod方法,就是将方法都加入到一个列表中,并与对应的class对应起来
//这里给object对应了三个方法hashcode,tostring和equals
addproxymethod(hashcodemethod, object.class);
addproxymethod(equalsmethod, object.class);
addproxymethod(tostringmethod, object.class);
//将接口列表中的接口与接口下的方法对应起来
for (int i = 0; i < interfaces.length; i++) {
method[] methods = interfaces[i].getmethods();
for (int j = 0; j < methods.length; j++) {
addproxymethod(methods[j], interfaces[i]);
}
}
/*
* for each set of proxy methods with the same signature,
* verify that the methods' return types are compatible.
*/
for (list<proxymethod> sigmethods : proxymethods.values()) {
checkreturntypes(sigmethods);
}
/*
* step 2: assemble fieldinfo and methodinfo structs for all of
* fields and methods in the class we are generating.
*/
//方法中加入构造方法,这个构造方法只有一个,就是一个带有invocationhandler接口的构造方法
//这个才是真正给class文件,也就是代理类加入方法了,不过还没真正处理,只是先加进来等待循环,构造方法在class文件中的名称描述是<init>
try {
methods.add(generateconstructor());
for (list<proxymethod> sigmethods : proxymethods.values()) {
for (proxymethod pm : sigmethods) {
//给每一个代理方法加一个method类型的属性,数字10是class文件的标识符,代表这些属性都是private static的
fields.add(new fieldinfo(pm.methodfieldname,
"ljava/lang/reflect/method;",
acc_private | acc_static));
//将每一个代理方法都加到代理类的方法中
methods.add(pm.generatemethod());
}
}
//加入一个静态初始化块,将每一个属性都初始化,这里静态代码块也叫类构造方法,其实就是名称为<clinit>的方法,所以加到方法列表
methods.add(generatestaticinitializer());
} catch (ioexception e) {
throw new internalerror("unexpected i/o exception");
}
//方法和属性个数都不能超过65535,包括之前的接口个数也是这样,
//这是因为在class文件中,这些个数都是用4位16进制表示的,所以最大值是2的16次方-1
if (methods.size() > 65535) {
throw new illegalargumentexception("method limit exceeded");
}
if (fields.size() > 65535) {
throw new illegalargumentexception("field limit exceeded");
}
//接下来就是写class文件的过程, 包括魔数, 类名,常量池等一系列字节码的组成,就不一一细说了。需要的可以参考jvm虚拟机字节码的相关知识。
cp.getclass(dottoslash(classname));
cp.getclass(superclassname);
for (int i = 0; i < interfaces.length; i++) {
cp.getclass(dottoslash(interfaces[i].getname()));
}
cp.setreadonly();
bytearrayoutputstream bout = new bytearrayoutputstream();
dataoutputstream dout = new dataoutputstream(bout);
try {
// u4 magic;
dout.writeint(0xcafebabe);
// u2 minor_version;
dout.writeshort(classfile_minor_version);
// u2 major_version;
dout.writeshort(classfile_major_version);
cp.write(dout); // (write constant pool)
// u2 access_flags;
dout.writeshort(acc_public | acc_final | acc_super);
// u2 this_class;
dout.writeshort(cp.getclass(dottoslash(classname)));
// u2 super_class;
dout.writeshort(cp.getclass(superclassname));
// u2 interfaces_count;
dout.writeshort(interfaces.length);
// u2 interfaces[interfaces_count];
for (int i = 0; i < interfaces.length; i++) {
dout.writeshort(cp.getclass(
dottoslash(interfaces[i].getname())));
}
// u2 fields_count;
dout.writeshort(fields.size());
// field_info fields[fields_count];
for (fieldinfo f : fields) {
f.write(dout);
}
// u2 methods_count;
dout.writeshort(methods.size());
// method_info methods[methods_count];
for (methodinfo m : methods) {
m.write(dout);
}
// u2 attributes_count;
dout.writeshort(0); // (no classfile attributes for proxy classes)
} catch (ioexception e) {
throw new internalerror("unexpected i/o exception");
}
return bout.tobytearray();
}
经过层层调用, 一个代理类终于生成了。
2、是谁调用了invoke?
我们模拟jdk自己生成一个代理类, 类名为testproxygen:
public class testgeneratorproxy {
public static void main(string[] args) throws ioexception {
byte[] classfile = proxygenerator.generateproxyclass("testproxygen", subject.class.getinterfaces());
file file = new file("/users/yadoao/desktop/testproxygen.class");
fileoutputstream fos = new fileoutputstream(file);
fos.write(classfile);
fos.flush();
fos.close();
}
}
用jd-gui反编译该class文件, 结果如下:
import com.su.dynamicproxy.isubject;
import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;
import java.lang.reflect.undeclaredthrowableexception;
public final class testproxygen extends proxy
implements isubject
{
private static method m3;
private static method m1;
private static method m0;
private static method m4;
private static method m2;
public testproxygen(invocationhandler paraminvocationhandler)
throws
{
super(paraminvocationhandler);
}
public final void sayhello()
throws
{
try
{
this.h.invoke(this, m3, null);
return;
}
catch (error|runtimeexception localerror)
{
throw localerror;
}
catch (throwable localthrowable)
{
throw new undeclaredthrowableexception(localthrowable);
}
}
public final boolean equals(object paramobject)
throws
{
try
{
return ((boolean)this.h.invoke(this, m1, new object[] { paramobject })).booleanvalue();
}
catch (error|runtimeexception localerror)
{
throw localerror;
}
catch (throwable localthrowable)
{
throw new undeclaredthrowableexception(localthrowable);
}
}
public final int hashcode()
throws
{
try
{
return ((integer)this.h.invoke(this, m0, null)).intvalue();
}
catch (error|runtimeexception localerror)
{
throw localerror;
}
catch (throwable localthrowable)
{
throw new undeclaredthrowableexception(localthrowable);
}
}
public final void saygoodbye()
throws
{
try
{
this.h.invoke(this, m4, null);
return;
}
catch (error|runtimeexception localerror)
{
throw localerror;
}
catch (throwable localthrowable)
{
throw new undeclaredthrowableexception(localthrowable);
}
}
public final string tostring()
throws
{
try
{
return (string)this.h.invoke(this, m2, null);
}
catch (error|runtimeexception localerror)
{
throw localerror;
}
catch (throwable localthrowable)
{
throw new undeclaredthrowableexception(localthrowable);
}
}
static
{
try
{
m3 = class.forname("com.su.dynamicproxy.isubject").getmethod("sayhello", new class[0]);
m1 = class.forname("java.lang.object").getmethod("equals", new class[] { class.forname("java.lang.object") });
m0 = class.forname("java.lang.object").getmethod("hashcode", new class[0]);
m4 = class.forname("com.su.dynamicproxy.isubject").getmethod("saygoodbye", new class[0]);
m2 = class.forname("java.lang.object").getmethod("tostring", new class[0]);
return;
}
catch (nosuchmethodexception localnosuchmethodexception)
{
throw new nosuchmethoderror(localnosuchmethodexception.getmessage());
}
catch (classnotfoundexception localclassnotfoundexception)
{
throw new noclassdeffounderror(localclassnotfoundexception.getmessage());
}
}
}
首先注意到生成代理类的构造函数, 它传入一个实现invokehandler接口的类作为参数, 并调用父类proxy的构造器, 即将proxy中的成员变量protected invokehander h进行了初始化。
再次注意到几个静态的初始化块, 这里的静态初始化块就是对代理的接口列表以及hashcode,tostring, equals方法进行初始化。
最后就是这几个方法的调用过程, 全都是回调invoke方法。
就此代理模式分析到此结束。
更多详解设计模式中的proxy代理模式及在java程序中的实现。
