设计模式之代理模式

设计模式之代理模式

代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作,即扩展目标对象的功能.举个栗子,比如你要调用别人的代码,想计算调用别人方法耗时多久,你不可能说要别人在里面添加统计耗时,你也不可能说在每个调用别人方法的时候在调用方法前和后计算耗时,这个时候你只要写个代理类,调用它的方法时调用这个代理类的方法就可以.

URL图如下

代码也很简单 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;

    }

   //给目标对象生成代理对象

    public Object getProxyInstance(){

    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)

throws Throwable {

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)) {

                // create proxy instance with doPrivilege as the proxy class may

                // implement non-public interfaces that requires a special permission

                return AccessController.doPrivileged(new PrivilegedAction<Object>() {

                    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(new Object[] {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) {

// TODO Auto-generated catch block

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<String> cache=new ArrayList<>();

   //给目标对象生成代理对象

    public Object getProxyInstance(){

    Object o=Proxy.newProxyInstance(

                target.getClass().getClassLoader(),

                target.getClass().getInterfaces(),

                new MyInvocationHandler(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)

throws Throwable {

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) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{

    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;

    }

    }

}

 

调用没变

ProxyFactory proxyFactory=new ProxyFactory(re);

Subject o= (Subject)proxyFactory.getProxyInstance();

o.sayHello();

o.request();

输出:

代理方法:sayHello

代理前操作...

sayHello

耗时:0ms

代理后操作...

RealSubject方法request被调用

可以看到需要计算的方法被计算了,不需要的还是原来的


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章