设计模式总览

菜鸟教程-设计模式简介


代理模式

https://www.bilibili.com/video/BV1D7411i7mT?p=238
image.png

  1. public class TestProxy {
  2. public static void main(String[] args) {
  3. UserDao userDao = new UserDao();
  4. UserDaoProxy userDaoProxy = new UserDaoProxy(userDao);
  5. userDaoProxy.add();
  6. }
  7. public interface Dao {
  8. void add();
  9. }
  10. //被代理类
  11. public static class UserDao implements Dao {
  12. @Override
  13. public void add() {
  14. System.out.println("添加用户");
  15. }
  16. }
  17. //代理类
  18. public static class UserDaoProxy implements Dao {
  19. private UserDao userDao;
  20. public UserDaoProxy(UserDao userDao) {
  21. this.userDao = userDao;
  22. }
  23. @Override
  24. public void add() {
  25. System.out.println("add()开始执行");
  26. long s = System.currentTimeMillis();
  27. //核心业务逻辑要交给被代理者完成
  28. userDao.add();
  29. long e = System.currentTimeMillis();
  30. System.out.println("add()执行结束");
  31. System.out.println("add()耗时(ms):" + (e-s));
  32. }
  33. }
  34. }