---
title: "java动态代理模式初解"
author: "aniu2008"
date: "2011-04-27T16:21:11Z"
tags: ["Java", "工作"]
categories: ["企业架构"]
slug: "java"
draft: false
lastmod: "2011-04-27T16:21:11Z"
id: 1020208
url: "https://aniu2008.iteye.com/blog/1020208"
---

**第一部分**  
                                                                                            
1.代理模式的作用和定义:  
      为其他对象提供一种代理以控制对这个对象的访问。在某些情况下，一个客户不想或者不能直接引用另一个对象，而代理对象可以在客户端和目标对象之间起到中介的作用。

 2.代理模式中涉及的角色  
  抽象角色:声明真实对象和代理对象的共同接口;一般声明为抽象类或是接口.

 代理角色：代理对象角色内部含有对真实对象的引用，从而可以操作真实对象，同时代理对象提供与真实对象相同的接口以便在任何时刻都能代替真实对象。同时，代理对象可以在执行真实对象操作时，附加其他的操作，相当于对真实对象进行封装。

 真实角色：代理角色所代表的真实对象，是我们最终要引用的对象。  
3.针对三种角色举个例子 抽象角色

![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)package proxypattern;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedBlock.gif)public interface Subject ...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)    
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)    public void dothing();  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockEnd.gif)}

真实角色,实现了Subject 的dothing()方法;

![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)package proxypattern;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedBlock.gif)public class RealSubject implements Subject...{  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)   public RealSubject()...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)       
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)   }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)    
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)   public void dothing()...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)       System.out.println("Do you want do.");  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)   }  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockEnd.gif)}

代理角色:  
  

![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)package proxypattern;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedBlock.gif)public class ProxySubject implements Subject...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)      
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)    public RealSubject realSubject;  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    public ProxySubject()...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)          
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)      
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    public void dothing()...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        predothing();  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)        if(realSubject==null)...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)            realSubject=new RealSubject();  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)        }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        realSubject.dothing();  //执行真实对象的dothing()方法  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        afterdothing();  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)      
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    private void predothing()...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        System.out.println("before you do thing!");  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    private void afterdothing()...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        System.out.println("after you do thing!");  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockEnd.gif)}

测试事例              

![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)package proxypattern;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedBlock.gif)public class ProxyTest ......{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    /\** \*//\** \*//\** \*//\**  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)     * @param args  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)     \*/  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    public static void main(String\[] args) ......{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)          
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        Subject sub=new ProxySubject();  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        sub.dothing();  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockEnd.gif)}

4.如果要按照上述的方法使用代理模式，那么真实角色必须是事先已经存在的，并将其作为代理对象的内部属性。但是实际使用时，  
一个真实角色必须对应一个代理角色，如果大量使用会导致类的急剧膨胀；此外，如果事先并不知道真实角色，该如何使用代理呢？  
这个问题可以通过Java的动态代理类来解决5.如果要按照上述的方法使用代理模式，那么真实角色必须是事先已经存在的，并将其作  
为代理对象的内部属性。但是实际使用时，一个真实角色必须对应一个代理角色，如果大量使用会导致类的急剧膨胀；此外，如果事  
先并不知道真实角色，该如何使用代理呢？这个问题可以通过Java的动态代理类来解决

**第二部分 .动态代理类**

Java动态代理类位于Java.lang.reflect包下，一般主要涉及到以下两个类：

(1). Interface InvocationHandler：该接口中仅定义了一个方法Object：invoke(Object obj,Method method, Object\[] args)。  
在实际使用时，第一个参数obj一般是指代理类，method是被代理的方法，如上例中的dothing()，args为该方法的参数数组。  
这个抽象方法在代理类中动态实现。

(2).Proxy：该类即为动态代理类，作用类似于上例中的ProxySubject，其中主要包含以下内容：

Protected Proxy(InvocationHandler h)：构造函数，估计用于给内部的h赋值。

Static Class getProxyClass (ClassLoader loader, Class\[] interfaces)：获得一个代理类，其中loader是类装载器，interfaces是真实  
类所拥有的全部接口的数组。

Static Object newProxyInstance(ClassLoader loader, Class\[] interfaces, InvocationHandler h)：返回代理类的一个实例，返回后  
的代理类可以当作被代理类使用(可使用被代理类的在Subject接口中声明过的方法)。

所谓Dynamic Proxy是这样一种class：它是在运行时生成的class，在生成它时你必须提供一组interface给它，然后该class就宣称它  
实现了这些 interface。你当然可以把该class的实例当作这些interface中的任何一个来用。当然啦，这个Dynamic Proxy其实就是  
一个Proxy，它不会替你作实质性的工作，在生成它的实例时你必须提供一个handler，由它接管实际的工作。

代理角色

![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)package dynamicproxy;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)import java.lang.reflect.InvocationHandler;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)import java.lang.reflect.Method;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedBlock.gif)public class DynamicSubject implements InvocationHandler ...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)      
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)public DynamicSubject() ...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)          
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)          
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)      
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    public DynamicSubject(Object obj) ...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)          
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        sub = obj;  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)      
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)    private Object sub;  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)    public Object invoke(Object proxy, Method method, Object\[] args)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)            throws Throwable ...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        // TODO Auto-generated method stub  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        System.out.println("before you do thing");  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        method.invoke(sub, args);  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        System.out.println("after you do thing");  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        return null;  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockEnd.gif)}  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)

该代理类的内部属性为Object类，实际使用时通过该类的构造函数DynamicSubject(Object obj)对其赋值；此外，  
在该类还实现了invoke方法，该方法中的

method.invoke(sub,args);

其实就是调用被代理对象的将要被执行的方法，方法参数sub是实际的被代理对象，args为执行被代理对象相应操作所需的参数。  
通过动态代理类，我们可以在调用之前或之后执行一些相关操作。

调用事例

![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)package dynamicproxy;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)import java.lang.reflect.InvocationHandler;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)import java.lang.reflect.Proxy;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)import proxypattern.RealSubject;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)import proxypattern.Subject;  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedBlock.gif)public class Client ...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    /\** \*//\**  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)     * @param args  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)     \*/  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockStart.gif)![](http://aniu2008.iteye.com/admin/blogs/img/ContractedSubBlock.gif)    public static void main(String\[] args) throws Throwable...{  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)        // TODO Auto-generated method stub  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)         RealSubject rs=new RealSubject();  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)         InvocationHandler ds=new DynamicSubject(rs);  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)         Class cls=rs.getClass();  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)         Subject subject=(Subject)Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),ds);  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)         subject.dothing();  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedSubBlockEnd.gif)    }  
![](http://aniu2008.iteye.com/admin/blogs/img/InBlock.gif)  
![](http://aniu2008.iteye.com/admin/blogs/img/ExpandedBlockEnd.gif)}  
![](http://aniu2008.iteye.com/admin/blogs/img/None.gif)

通过这种方式，被代理的对象(RealSubject)可以在运行时动态改变，需要控制的接口(Subject接口)可以在运行时改变，  
控制的方式(DynamicSubject类)也可以动态改变，从而实现了非常灵活的动态代理关系。