设计模式之代理模式运用
代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作,即扩展目标对象的功能
举个栗子,比如你要调用别人的代码,想计算调用别人方法耗时多久,你不可能说要别人在里面添加统计耗时,你也不可能说在每个调用别人方法的时候在调用方法前和后计算耗时,这个时候你只要写个代理类,调用它的方法时调用这个代理类的方法就可以.
类图关系如下
代码也很简单,要代理的Subject接口
public interface Subject {
String request();
}
代理类Proxy,实现接口
public class Proxy implements Subject{
private Subject realSubject;
public Proxy(Subject s){
realSubject=s;
}
@Override
public String request() {
System.out.println("代理前操作...");
long start=System.currentTimeMillis();
String requst=realSubject.request();
long end=System.currentTimeMillis();
System.out.println("耗时:"+(end-start)+"ms");
System.out.println("代理后操作...");
return requst;
}
}
被代理的类,也实现同样的接口
public class RealSubject implements Subject{
@Override
public String request() {
System.out.println("RealSubject方法request被调用");
Random random=new Random();
try{
Thread.sleep(random.nextInt(1000));//模拟耗时操作
}catch(InterruptedException e) {
e.printStackTrace();
}
return "这是RealSubject request调用后返回的结果";
}
}
测试类
public class HelloWorld {
public static void main(String[] args) {
RealSubject re=new RealSubject();
Proxy pro=new Proxy(re);
System.out.println(pro.request());;
}
}
输出结果:
代理前操作...
RealSubject方法request被调用
耗时:936ms
代理后操作...
这是RealSubject request调用后返回的结果
这样做的完全实现了代理的功能,但是带来的缺点也很明显,就是要多个代码类处理了。要是很多类需要代理,那难道要写很多个代理类出来??
针对这个缺点,动态代理也就随之而出了
类:
/**
*创建动态代理对象
*动态代理不需要实现接口,但是需要指定接口类型
*/
public class ProxyFactory{
//维护一个目标对象
private Object target;
public ProxyFactory(Object target){
this.target=target;
}
//给目标对象生成代理对象,这个类就相当于Proxy
public Object getProxyInstance(){
//根据target的实现的接口生成一个代理对象
Object o=Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new MyInvocationHandler(target));
return o;
}
class MyInvocationHandler implements InvocationHandler{
private Object target;
MyInvocationHandler(Object o){
target=o;
}
//关键方法,所有调用代理类实现的接口方法时,都会从此方法调用
@Override
public Object invoke(Object proxy, Method method, Object[] args)throwsThrowable {
System.out.println("代理方法:"+method.getName());
System.out.println("代理前操作...");
long start=System.currentTimeMillis();
Object returnValue=method.invoke(target, args);//执行目标对象方法
long end=System.currentTimeMillis();
System.out.println("耗时:"+(end-start)+"ms");
System.out.println("代理后操作...");
return returnValue;
}
}
}
调用:
RealSubject re=new RealSubject();
ProxyFactory proxyFactory=new ProxyFactory(re);
Subject o=(Subject) proxyFactory.getProxyInstance();
System.out.println(o.request());
输出:
代理方法:request
代理前操作...
RealSubject方法request被调用
耗时:203ms
代理后操作...
这是RealSubject request调用后返回的结果
结果和前面一个.
既然是代理RealSubject类,那是不是强转为RealSubject是不是也行呢?本着好奇,我这样写:
RealSubject o=(RealSubject) proxyFactory.getProxyInstance();
结果报异常
java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to RealSubject
于是我又打印代理的类
Object o= proxyFactory.getProxyInstance();
System.out.println(o.toString());
输出:RealSubject@5c3f1224
看起来好像也是RealSubject类一样,But我强制转换的时候为啥报错了呢,难道此RealSubject对象非我自己写的RealSubject类??
于是乎我打印它里面的所有方法:
for(Method m:o.getClass().getMethods()){
System.out.print(m.getName()+”,”);
}
equals,toString,hashCode,request,isProxyClass,getInvocationHandler,getProxyClass,newProxyInstance,wait,wait,wait,getClass,notify,notifyAll
里面多了几个方法
我又把他们的class name打印出来
System.out.println(o.getClass().getName());
System.out.println(re.getClass().getName());
输出:
com.sun.proxy.$Proxy0
com.test.RealSubject
原来它的class是这样子的啊,难怪它产生的对象里面的方法还多出几个,为啥是这样子的呢,
点进去Proxy.newProxyInstance
方法里面去看
public static Object newProxyInstance(ClassLoader loader,Class[] interfaces,InvocationHandler h)throws IllegalArgumentException{
if(h ==null) {
throw new NullPointerException();
}
final Class[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if(sm !=null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
//根据要代理的接口生成代理类class
Class cl =getProxyClass0(loader, intfs);
try{
//生成构造器,待会利用这个构造器去生成实例
final Constructor cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if(sm !=null&& ProxyAccessHelper.needsNewInstanceCheck(cl)) {
return AccessController.doPrivileged(newPrivilegedAction() {
public Object run() {
//在这个返回一个实现interfaces接口的实例对象
return newInstance(cons, ih);
}
});
}else{
return newInstance(cons, ih);
}
}catch(NoSuchMethodException e) {
throw new InternalError(e.toString());
}
}
private static Object newInstance(Constructor cons, InvocationHandler h) {
try{
return cons.newInstance(newObject[] {h} );
}catch(IllegalAccessException | InstantiationException e) {
throw new InternalError(e.toString());
}catch(InvocationTargetException e) {
Throwable t = e.getCause();
if( t instanceof RuntimeException) {
throw(RuntimeException) t;
}else{
throw new InternalError(t.toString());
}
}
}
看完源码才恍然大悟,原来它是自己生成了class对象,class对象根据传入参数interfaces接口,实现interfaces的所有方法,这样要代理哪个接口的方法就传入哪个接口的方法.newProxyInstance(ClassLoader loader,Class[] interfaces,InvocationHandler h)
后来又想,要是有些方法需要计算时间,有些方法不需要那咋操作了.
于是想到了注解,把注解添加进去
/**
*被该注解标明的方法需要计算方法耗时
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CompteTime{
}
Subject接口有两个方法,一个需要计算,一个不需要计算的
public interface Subject {
String request();
String sayHello();
}
RealSubject这个类就是这样的.
public class RealSubject implements Subject{
public String say(){
System.out.println("sayHello");
return"sayHello";
}
@Override
public String request() {
System.out.println("RealSubject方法request被调用");
Random random=new Random();
try{
Thread.sleep(random.nextInt(1000));
}catch(InterruptedException e) {
e.printStackTrace();
}
return "这是RealSubject request调用后返回的结果";
}
@CompteTime
@Override
public String sayHello() {
System.out.println("sayHello");
return"sayHello";
}
}
ProxyFactory类
public class ProxyFactory{
//维护一个目标对象
private Object target;
public ProxyFactory(Object target){
this.target=target;
}
private List cache=new ArrayList<>();
//给目标对象生成代理对象
public Object getProxyInstance(){
Object o=Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),newMyInvocationHandler(target)
);
for(Method m:target.getClass().getMethods()){
Annotation[] annotations=m.getAnnotations();
for(Annotation a:annotations){
if(a instanceof CompteTime){
if(!cache.contains(m.getName())){
cache.add(m.getName());
}
}
}
}
return o;
}
class MyInvocationHandler implements InvocationHandler{
private Object target;
MyInvocationHandler(Object o){
target=o;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)throwsThrowable {
System.out.println("invoke:"+proxy.getClass().getName());
boolean isComputeleTime=false;
if(cache.contains(method.getName())){
isComputeleTime=true;
}
if(isComputeleTime){
return comleteTime(method,args);
}else{
return method.invoke(target, args);
}
}
private Object comleteTime(Method method,Object[] args)throwsIllegalAccessException, IllegalArgumentException, InvocationTargetException{
System.out.println("代理方法:"+method.getName());
System.out.println("代理前操作...");
longstart=System.currentTimeMillis();
Object returnValue=method.invoke(target, args);//执行目标对象方法
longend=System.currentTimeMillis();
System.out.println("耗时:"+(end-start)+"ms");
System.out.println("代理后操作...");
return returnValue;
}
}
调用没变
ProxyFactory proxyFactory=newProxyFactory(re);
Subject o= (Subject)proxyFactory.getProxyInstance();
o.sayHello();
o.request();
输出:
代理方法:sayHello
代理前操作...
sayHello
耗时:0ms
代理后操作...
RealSubject方法request被调用
可以看到被CompteTime注解修饰的方法自动添加了耗时计算操作,并且不影响原来的方法业务逻辑,更不用在原来的方法里面插入代码。
但是也有个局限,就是只能作用于被代理类实现了接口的方法,如果没有实现接口的方法,则无法使用,这也是动态代理的局限。难道还有其他可以突破这个局限的?借助AOP可以实现类方法的任何代理。后面再介绍AOP方式实现方式