java静态代理与动态代理用法

代理模式是指通过代理对象来访问目标对象,这样便于在目标对象的功能基础之上添加额外的功能扩展,并且不需要改变原目标对象的代码。

1、静态代理

静态代理比较简单,代理类与目标类实现同一个接口,把目标类的对象添加进代理类中,然后在代理类的方法中调用目标类的方法,代码如下:

接口

public interface People {
void eat();

}

目标类

public class Student implements People{
@Override
public void eat() {
System.out.println("在学校食堂吃饭");
}

}

代理类

public class StudentProxy implements People{
private Student student;
public StudentProxy(Student student)
{
this.student = student;
}
@Override
public void eat() {
System.out.println("前拦截");
student.eat();
System.out.println("后拦截");
}

}

测试类:

public class Test {
public static void main(String[] args) {
Student student = new Student();
StudentProxy studentProxy = new StudentProxy(student);
studentProxy.eat();
}

}

执行结果:

前拦截
在学校食堂吃饭

后拦截

优点:在不改变原有目标类的情况下,扩展目标类的功能

缺点:因为代理类也需要实现接口,所以当接口中方法一多,代理类也需要重新维护,但是往往我们可能只需要代理目标类中某一个方法,这种情况下,使用静态代理就比较麻烦,可以使用动态代理

2、动态代理

接口

public interface People {
void eat();

}

目标类

public class Student implements People{
@Override
public void eat() {
System.out.println("在学校食堂吃饭");
}

}

动态代理类

public class DynamicProxy implements InvocationHandler{
private People people;
public DynamicProxy(People people) {
this.people = people;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("动态代理拦截前");
method.invoke(people, args);
System.out.println("动态代理拦截后");
return null;
}

}

测试类

public class Test {
public static void main(String[] args) {
People student = new Student();
DynamicProxy dynamicProxy = new DynamicProxy(student);
People proxy = (People) Proxy.newProxyInstance(student.getClass().getClassLoader(), new Class[]{People.class}, dynamicProxy);
proxy.eat();
}
}

运行结果:

动态代理拦截前
在学校食堂吃饭

动态代理拦截后

优点:当接口增加方法时,代理类并不需要重新维护。

猜你喜欢

转载自blog.csdn.net/zhenwei1994/article/details/79851804