一、静态代理
1、概述: <1>作用: 可以不修改目标对象而对其功能进行扩展; <2>要求(核心思想):需要定义一个接口父类,目标对象与代理对象一起实现相同的接口或者是继承相同父类; 代理类需要有个静态成员属性:目标类的对象,在使用时,需要创建接口对象然后用代理对象给他赋值; <3>Code: (1)定义接口
interface Father{ target_method1; target_method2; ...... }(2) 定义目标类:
class target_class implement Father{ target_method1{ target function section; } target_method2{ target function section; } ........ }(3) 定义代理类:
public class proxy_class implement Father{ private target_class target_instance; public class proxy_class(target_class target_instance){ this.target_instance = target_instance; target_method1{ extend function section; target function section -> this.target_instance.method1; extend function section; } target_method2{ extend function section; //扩展区 target function section -> this.target_instance.method2; extend function section; //扩展区 } ........ }(4)使用静态代理:
Father father = new proxy_class(new target_class()); father.target_method1; father.target_method2; ...........因为代理对象和目标对象都实现了同一个接口,而声明的接口的对象,将代理类的对象上转给他,之后使用的就是代理对象的方法,而代理对象里面调用了目标对象的方法并加了扩展的功能;
二、动态代理: 1、概述: <1>作用: 可以不修改目标对象而对其功能进行扩展,并且不需要自己创建代理类,直接通过一个代理类工厂在内存自动生成; <2>要求(核心思想):需要定义一个接口父类,目标对象实现接口;再创建一个代理工厂,代理工厂需要一个成员属性(Object类的对象),需要有个静态成员属性,之后用newProxyInstance()获取代理对象,需要实现InvocationHandler接口的invoke方法来实现扩展功能; <3>Code: (1)定义接口:
nterface Father{ target_method1; target_method2; ...... }(2) 定义目标类:
class target_class implement Father{ target_method1{ target function section; } target_method2{ target function section; } ........ }(3)定义代理工厂
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactoryJDK { private Object target; public ProxyFactoryJDK(Object target) { this.target = target; } public Object getProxy() { ClassLoader loader = target.getClass().getClassLoader(); Class<?>[] interfaces = target.getClass().getInterfaces(); Object object = Proxy.newProxyInstance(loader, interfaces, new InvocationHandler(){ public Object invoke(Object proxy, Method method, Object[] args) { ExtendFunction Section; Object result = method.invoke(target, args); //调用target类的方法 method,参数为args ExtendFunction Section; return result; } }); return object; } }(4)使用代理工厂代理:
Father father = (Father)new ProxyFactoryJDK(new target_class()).getProxy(); father.method1(); farher.method2(); .................