基本介绍

image.png


静态代理

image.png
image.png


动态代理

image.png

  1. public interface ITeacherDao {
  2. void teach();
  3. }
  1. public class TeacherDao implements ITeacherDao {
  2. @Override
  3. public void teach() {
  4. System.out.println("teach");
  5. }
  6. }
  1. public class ProxyFactory {
  2. private Object target;
  3. public ProxyFactory(Object target) {
  4. this.target = target;
  5. }
  6. public Object getProxyInstance() {
  7. return Proxy.newProxyInstance(target.getClass().getClassLoader(),
  8. target.getClass().getInterfaces(),
  9. (proxy, method, args) -> {
  10. System.out.println("JDK代理开始");
  11. Object returnVal = method.invoke(target, args);
  12. return returnVal;
  13. });
  14. }
  15. }
  1. public class Client {
  2. public static void main(String[] args) {
  3. //创建目标对象
  4. ITeacherDao target = new TeacherDao();
  5. //给目标对象创建代理对象
  6. ProxyFactory proxyFactory = new ProxyFactory(target);
  7. ITeacherDao proxyInstance = (ITeacherDao) proxyFactory.getProxyInstance();
  8. proxyInstance.teach();
  9. }
  10. }