image-20200725093338559.png

静态代理

  1. //静态代理
  2. public class Tank implements movable{
  3. @Override
  4. public void move() {
  5. System.out.println("调用了move方法");
  6. try {
  7. Thread.sleep(1000);
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }
  13. class MoveTimeProxy implements movable{
  14. movable m;
  15. public MoveTimeProxy(movable m) {
  16. this.m = m;
  17. }
  18. @Override
  19. public void move() {
  20. long start = System.currentTimeMillis();
  21. m.move();
  22. long end = System.currentTimeMillis();
  23. System.out.println("运行时间:"+(end-start));
  24. }
  25. }
  26. class MoveLogProxy implements movable{
  27. movable m;
  28. public MoveLogProxy(movable m) {
  29. this.m = m;
  30. }
  31. @Override
  32. public void move() {
  33. System.out.println("start move");
  34. m.move();
  35. System.out.println("move end");
  36. }
  37. public static void main(String[] args) {
  38. new MoveLogProxy(new MoveTimeProxy(new Tank())).move();
  39. }
  40. }
  41. interface movable{
  42. public void move();
  43. }

动态代理

image-20200725135631693.png

  1. //静态代理
  2. public class Tank implements movable{
  3. @Override
  4. public void move() {
  5. System.out.println("调用了move方法");
  6. try {
  7. Thread.sleep(1000);
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. public static void main(String[] args) {
  13. Tank tank = new Tank();
  14. movable movable = (movable) Proxy.newProxyInstance(
  15. Tank.class.getClassLoader(),
  16. new Class[]{movable.class},
  17. new LogHander(tank));
  18. movable.move();
  19. }
  20. }
  21. class LogHander implements InvocationHandler{
  22. Tank tank;
  23. public LogHander(Tank tank) {
  24. this.tank = tank;
  25. }
  26. @Override
  27. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  28. System.out.println("method:"+method.getName()+"start");
  29. Object invoke = method.invoke(tank, args);
  30. System.out.println("method:"+method.getName()+"end");
  31. return invoke;
  32. }
  33. }
  34. interface movable{
  35. public void move();
  36. }