代理模式

什么是代理模式

代理模式分为

  • 远程代理:为不同地理的对象提供局域网代表对象
  • 虚拟代理:将资源消耗大的对象进行延迟,需要的时候才创建
  • 保护代理:控制对一个对象的访问权限
  • 智能引用代理:提供对目标对象额外服务

JDK静态代理

感觉就是装饰模式+模版方法模式,代理类(Driver)和被代理类(Boss)实现相同的接口(Drivable),并把被代理类(Boss)注入到代理类(Driver)中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public interface Drivable{
void drive();
}

public class Boss implements Drivable{
public void drive(){
System.out.println("老板想开车");
}
}

public class Driver implements Drivable{
private Drivable boss;
public Driver(Drivable boss){
this.boss = boss;//注入被代理类
}
public void drive(){
System.out.println("司机来开车");
boss.drive();
System.out.println("司机已停车");
}
}

public class Main{
public static void main(String[] args){
Boss boss = new Boss();
Driver driver = new Driver(boss);
driver.drive();
}
}

JDK动态代理

通过一个实现了InvocationHandler接口的类进行代理。在invoke方法中实现业务逻辑处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class DriverHandler implements InvocationHandler{
private Object target;
public DriverHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
System.out.println("司机来开车");
method.invoke(target,args);
System.out.println("司机已停车");
return null;
}
}
public class Main{
public static void main(String[] args){
Boss boss = new Boss();
DriverHandler handler = new DriverHandler(boss);
Drivable drivable = (Drivable) Proxy.newProxyInstance(
boss.getClass().getClassLoader(), boss.getClass().getInterfaces(), handler);
drivable.drive();
}
}

CGLIB动态代理

CGLIB是通过继承实现的动态代理
先导入maven

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/cglib/cglib-nodep -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.5</version>
</dependency>

编写代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Boss {
public void drive(){
System.out.println("老板想开车");
}
}
public class CglibProxy implements MethodInterceptor {
private Enhancer enhancer = new Enhancer();
public Object getProxy(Class clazz){
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}

@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("司机来开车");
proxy.invokeSuper(obj, args);
System.out.println("司机已停车");
return null;
}
}
public class Main{
public static void main(String[] args){
CglibProxy proxy = new CglibProxy();
Boss boss = (Boss) proxy.getProxy(Boss.class);
boss.drive();
}
}