静态代理模式

想象一个场景:现在我们要计算一个给定包中的一个类Tank的放run()的运行时间,并不是计算new Tank().run()的时间,因为new包含JDK实例化的时间。这里要求是纯粹计算run方法的时间。方法有两种:继承和聚合。

1、继承

 1 package program.proxy.model;
 2 import program.factory.model.Moveable;
 3 public class Tank implements Moveable{
 4     public void run() {
 5        System.out.println("Tank Moving 。。。");
 6        try {
 7         Thread.sleep(10000);
 8     } catch (InterruptedException e) {
 9         e.printStackTrace();
10     }
11     }
12 }
13 
14 
15 public class TankTimeProxy extends Tank{
16      public void run() {
17          long start=System.currentTimeMillis();
18          super.run();
19          long end=System.currentTimeMillis();
20          System.out.println((end-start)/1000);
21      }
22 }
23 
24 public class Main {
25     public static void main(String[]args) {
26         TankTimeProxy ttp=new TankTimeProxy();
27         ttp.run();
28     }
29 }

 

2、聚合

 1 package program.proxy.model;
 2 public class TankTimeProxy extends Tank{
 3     Tank t;
 4     public TankTimeProxy(Tank t) {
 5         this.t=t;
 6     }
 7      public void run() {
 8          long start=System.currentTimeMillis();
 9          t.run();
10          long end=System.currentTimeMillis();
11          System.out.println((end-start)/1000);
12      }
13 }
14 
15 public class Main {
16     public static void main(String[]args) {
17         Tank t=new Tank();
18         TankTimeProxy ttp=new TankTimeProxy(t);
19         ttp.run();
20     }
21 }

 

上面两种形式都是静态代理模式,代理即呈现给用户的虽然是TankTimeProxy当中的run方法,但实质上调用的还是Tank当中的move方法。只是TankTimeProxy的run方法在调用实质的run方法的前后作了一些特殊的处理。

 基于上面两种实现代理的方法,第二种聚合的方式更加灵活。假设我们要增加一个新的需求,在记录时间前先记录日志。如果加上日志记录后,又要记录权限,且它们的记录顺序还可能随时变化,那么继承方式实现的代理就会导致类的不断增加。而聚合能很好的实现扩展。

 1 public class TankLogProxy implements Moveable{
 2     Moveable t;
 3     public TankLogProxy(Moveable t) {
 4         this.t=t;
 5     }
 6     @Override
 7     public void run() {
 8         System.out.println("Log start 。。。");
 9         t.run();
10         System.out.println("Log end 。。。");
11     }
12 }
13 
14 
15 public class Main {
16     public static void main(String[]args) {
17         Tank t=new Tank();
18         TankTimeProxy ttp=new TankTimeProxy(t);
19         TankLogProxy tlp=new TankLogProxy(ttp);
20         tlp.run();
21     }
22 }

 

posted on 2014-05-03 20:21  飞机说之代码也疯狂  阅读(370)  评论(0编辑  收藏  举报