什么是代理模式?
为其他对象提供一种代理以控制对这个对象的访问。——《Java设计模式》
■ 抽象主题(Subject)角色:该角色是真实主题和代理主题的共同接口,以便在任何可以使用真实主题的地方都可以使用代理主题。
■ 代理主题(Proxy Subject)角色:也叫做委托类、代理类,该角色
1)负责控制对真实主题的引用,
2)负责在需要的时候创建或删除真实主题对象
3)在真实主题角色处理完毕前后做预处理和善后处理工作。
■ 真实主题(Real Subject)角色:该角色也叫做被委托角色、被代理角色,是业务逻辑的具体执行者。
1.静态代理
Java中的静态代理要求代理类(ProxySubject)和委托类(RealSubject)都实现同一个接口(Subject)。
1)静态代理中代理类在编译期就已经确定。
2)静态代理的效率相对动态代理来说相对高一些
3)静态代理代码冗余大,一单需要修改接口,代理类和委托类都需要修改。
举例:
接口 Developer:
public interface Developer {
void coding();
void debug();
}
委托类 AndroidDeveloper:
public class AndroidDeveloper implements Developer{
private String name;
public AndroidDeveloper(String name){
this.name = name;
}
public String getDeveloperName(){
return name;
}
@Override
public void coding(){
System.out.println("Coding: "+this.name+" is developing Android!");
}
@Override
public void debug(){
System.out.println("Coding: "+this.name+" is debugging his APP!");
}
}
静态代理类 JavaStaticProxy
public class JavaStaticProxy implements Developer{
private Developer target;
public JavaStaticProxy(Developer developer){
this.target = developer;
}
@Override
public void coding() {
System.out.println("before!");
this.target.coding();
System.out.println("after!");
}
@Override
public void debug() {
System.out.println("before!");
this.target.debug();
System.out.println("after!");
}
}
测试:
public class Main {
public static void main(String[] args){
StaticProxyTest();
}
public static void StaticProxyTest(){
System.out.println("StaticProxy:");
Developer Breeze = new AndroidDeveloper("Breeze");
JavaStaticProxy staticProxy = new JavaStaticProxy(Breeze);
staticProxy.coding();
staticProxy.debug();
}
}
输出:
StaticProxy:
before!
Coding: Breeze is developing Android!
after!
before!
Coding: Breeze is debugging his APP!
after!
2.动态代理
Java中的动态代理依靠反射来实现,代理类和委托类不需要实现同一个接口。委托类需要实现接口,否则无法创建动态代理。代理类在JVM运行时动态生成,而不是编译期就能确定。
Java动态代理主要涉及到两个类:java.lang.reflect.Proxy和java.lang.reflect.InvocationHandler。代理类需要实现InvocationHandler接口或者创建匿名内部类,而Proxy用于创建动态动态。
https://www.jianshu.com/p/f56e123817b5
特点:
1)不要求代理类与委托类实现统一接口,避免了静态代理生成大量代理类的问题,但比较消耗性能。
2)可以非常灵活地在某个类,某个方法,某个代码点上切入我们想要的内容,就是动态代理其中的内容。
2.1 例子:
动态代理类 JavaDynamicProxy
package java_proxy;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class JavaDynamicProxy {
private Developer target;
public JavaDynamicProxy(Developer target){
this.target = target;
}
public Object getDeveloperProxy(){
Developer developerProxy = (Developer) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().
getInterfaces(), (proxy, method, args1) -> {
Field field = target.getClass().getDeclaredField("name");
field.setAccessible(true);
String name = (String) field.get(target);
if(method.getName().equals("coding")){
beforeCoding(name);
method.invoke(target, args1);
afterCoding(name);
}
if(method.getName().equals("debug")){
beforeDebug(name);
method.invoke(target, args1);
afterDebug(name);
}
return null;
});
return developerProxy;
}
public void beforeCoding(String name){
System.out.println("Before coding: "+name+" is very happy!");
}
public void afterCoding(String name){
System.out.println("After coding: "+name+" is very tired!");
}
public void beforeDebug(String name){
System.out.println("Before debugging: "+name+"'s App has no bug! Nobody knows Android better than me!");
}
public void afterDebug(String name){
System.out.println("After debugging: What trash is "+name+"?");
}
}
测试:
package java_proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args){
DynamicProxyTest();
}
public static void DynamicProxyTest(){
System.out.println("DynamicProxy:");
AndroidDeveloper target = new AndroidDeveloper("Breeze");
Developer proxy = (Developer)new JavaDynamicProxy(target).getDeveloperProxy();
proxy.coding();
proxy.debug();
}
}
输出:
DynamicProxy:
Before coding: Breeze is very happy!
Coding: Breeze is developing Android!
After coding: Breeze is very tired!
Before debugging: Breeze's App has no bug! Nobody knows Android better than me!
Coding: Breeze is debugging his APP!
After debugging: What trash is Breeze?
2.2 动态代理的原理
Proxy.newProxyInstance()
把接口复制出来,通过这些接口和类加载器,拿到这个代理类cl。然后通过反射的技术复制拿到代理类的构造函数(这部分代码在Class类中的getConstructor0方法),最后通过这个构造函数new个一对象出来,同时用InvocationHandler绑定这个对象。
/* @param loader the class loader to define the proxy class
* @param interfaces the list of interfaces for the proxy class
* to implement
* @param h the invocation handler to dispatch method invocations to
* @return a proxy instance with the specified invocation handler of a
* proxy class that is defined by the specified class loader
* and that implements the specified interfaces
* @throws IllegalArgumentException if any of the
* restrictions on the parameters are violated
* @throws SecurityException if a security manager, s, is present
* and any of the following conditions is met:
*
* - the given {@code loader} is {@code null} and
* the caller's class loader is not {@code null} and the
* invocation of {@link SecurityManager#checkPermission
* s.checkPermission} with
* {@code RuntimePermission("getClassLoader")} permission
* denies access;
* - for each proxy interface, {@code intf},
* the caller's class loader is not the same as or an
* ancestor of the class loader for {@code intf} and
* invocation of {@link SecurityManager#checkPackageAccess
* s.checkPackageAccess()} denies access to {@code intf};
* - any of the given proxy interfaces is non-public and the
* caller class is not in the same {@linkplain Package runtime package}
* as the non-public interface and the invocation of
* {@link SecurityManager#checkPermission s.checkPermission} with
* {@code ReflectPermission("newProxyInPackage.{package name}")}
* permission denies access.
*
* @throws NullPointerException if the {@code interfaces} array
* argument or any of its elements are {@code null}, or
* if the invocation handler, {@code h}, is
* {@code null}
*
* @see Package and Module Membership of Proxy Class
* @revised 9
* @spec JPMS
*/
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class>[] interfaces,
InvocationHandler h) {
Objects.requireNonNull(h);
final Class> caller = System.getSecurityManager() == null
? null
: Reflection.getCallerClass();
/*
* Look up or generate the designated proxy class and its constructor.
*/
Constructor> cons = getProxyConstructor(caller, loader, interfaces);
return newProxyInstance(caller, cons, h);
}
InvocationHandler
InvocationHandler作用就是,当代理对象的原本方法被调用的时候,会绑定执行一个方法,这个方法就是InvocationHandler里面定义的内容,同时会替代原本方法的结果返回。
InvocationHandler接收三个参数
- proxy,代理后的实例对象。
- method,对象被调用方法。
- args,调用时的参数。
public interface InvocationHandler {
/**
* Processes a method invocation on a proxy instance and returns
* the result. This method will be invoked on an invocation handler
* when a method is invoked on a proxy instance that it is
* associated with.
*
* @param proxy the proxy instance that the method was invoked on
*
* @param method the {@code Method} instance corresponding to
* the interface method invoked on the proxy instance. The declaring
* class of the {@code Method} object will be the interface that
* the method was declared in, which may be a superinterface of the
* proxy interface that the proxy class inherits the method through.
*
* @param args an array of objects containing the values of the
* arguments passed in the method invocation on the proxy instance,
* or {@code null} if interface method takes no arguments.
* Arguments of primitive types are wrapped in instances of the
* appropriate primitive wrapper class, such as
* {@code java.lang.Integer} or {@code java.lang.Boolean}.
*
* @return the value to return from the method invocation on the
* proxy instance. If the declared return type of the interface
* method is a primitive type, then the value returned by
* this method must be an instance of the corresponding primitive
* wrapper class; otherwise, it must be a type assignable to the
* declared return type. If the value returned by this method is
* {@code null} and the interface method's return type is
* primitive, then a {@code NullPointerException} will be
* thrown by the method invocation on the proxy instance. If the
* value returned by this method is otherwise not compatible with
* the interface method's declared return type as described above,
* a {@code ClassCastException} will be thrown by the method
* invocation on the proxy instance.
……
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}