一、概述
1.目标:要在Tank的move()方法做时间代理及日志代理(可以设想以后还要增加很多代理处理),且代理间的顺序可活更换
2.思路:
(1)聚合:由于代理类及被代理类都实现了movable接口,代理类聚合了被代理类,所以可以灵活多变,具体看代码
(2)继承:继承不够灵活,具体看代码
二、代码
1.Movable.java
2.Tank.java
3.TankTimeProxy.java
4.TankLogProxy.java
5.Tank2Time.java
6.Tank3Log.java
7.Client.java
1.Movable.java
1 public interface Movable { 2 public void move(); 3 }
2.Tank.java
1 import java.util.Random; 2 3 public class Tank implements Movable { 4 5 @Override 6 public void move() { 7 System.out.println("Tank moving......."); 8 try { 9 Thread.sleep(new Random().nextInt(5000)); 10 } catch (InterruptedException e) { 11 e.printStackTrace(); 12 } 13 } 14 15 }
3.TankTimeProxy.java
1 public class TankTimeProxy implements Movable { 2 3 Movable m; 4 5 public TankTimeProxy(Movable m) { 6 this.m = m; 7 } 8 9 @Override 10 public void move() { 11 System.out.println("Time Proxy start..........."); 12 long start = System.currentTimeMillis(); 13 m.move(); 14 long end = System.currentTimeMillis(); 15 System.out.println("花费时间:"+(end - start)); 16 System.out.println("Time Proxy end..........."); 17 } 18 19 }
4.TankLogProxy.java
1 public class TankLogProxy implements Movable { 2 3 Movable m; 4 5 public TankLogProxy(Movable m) { 6 this.m = m; 7 } 8 9 @Override 10 public void move() { 11 System.out.println("Log Proxy start..........."); 12 m.move(); 13 System.out.println("Log Proxy end..........."); 14 } 15 16 }
5.Tank2Time.java
1 public class Tank2Time extends Tank { 2 3 public void move(){ 4 System.out.println("Tank2 time start..........."); 5 long start = System.currentTimeMillis(); 6 super.move(); 7 long end = System.currentTimeMillis(); 8 System.out.println("花费时间:"+(end - start)); 9 System.out.println("Tank2 time end..........."); 10 } 11 }
6.Tank3Log.java
1 public class Tank3Log extends Tank2Time { 2 3 public void move(){ 4 System.out.println("Tank3Log start..........."); 5 super.move(); 6 System.out.println("Tank3Log end..........."); 7 } 8 }
7.Client.java
1 public class Client { 2 3 @Test 4 public void testProxy(){ 5 6 Tank t = new Tank(); 7 Movable m; 8 9 //一、聚合的方式(较灵活,因为实现了接口) 10 //1.1聚合方式的代理,先日志代理,后时间代理 11 TankTimeProxy ttp1 = new TankTimeProxy(t); 12 TankLogProxy tlp1 = new TankLogProxy(ttp1); 13 14 m = tlp1; 15 m.move(); 16 17 System.out.println("\n==============================分隔线==========================\n"); 18 19 //1.2聚合方式的代理,先时间代理,后日志代理(可以灵活切换顺序) 20 TankLogProxy tlp2 = new TankLogProxy(t); 21 TankTimeProxy ttp2 = new TankTimeProxy(tlp2); 22 23 m = ttp2; 24 m.move(); 25 26 System.out.println("\n==============================分隔线==========================\n"); 27 28 //二、继承的方式 29 //2.1代理时间 30 Tank2Time t2 = new Tank2Time(); 31 t2.move(); 32 33 System.out.println("\n==============================分隔线==========================\n"); 34 35 //2.2先代理日志,后时间,不能灵活切换 36 Tank3Log t3 = new Tank3Log(); 37 t3.move(); 38 39 40 41 } 42 }
三、运行结果
四、小结
凡是要求灵活多变的功能,多数用接口多态实现
时间: 2024-11-06 07:17:58