(1)创建接口
package com.strategy;
public interface Moveable {
void move();
}
(2)log
package com.strategy;
public class TankLogProxy implements Moveable{
public TankLogProxy(Moveable t) {
super();
this.t = t;
}
Moveable t;
public void move() {
// TODO Auto-generated method stub
System.out.println("Tank start...");
t.move();
System.out.println("Tank stop...");
}
}
(3)使用用聚合的方法取时间
package com.strategy;
//用聚合的方法取时间
public class TankTimeProxy implements Moveable{
public TankTimeProxy(Moveable t) {
super();
this.t = t;
}
Moveable t;
public void move() {
// TODO Auto-generated method stub
long start = System.currentTimeMillis(); //取开始时间
System.out.println("starttime:"+(start));
t.move();
long end = System.currentTimeMillis();//取结束时间
System.out.println("time:"+(end-start)); //打印出执行方法用的时间
}
}
(4)测试输出
package com.strategy;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Tank t = new Tank();
TankTimeProxy ttp = new TankTimeProxy(t);
TankLogProxy tlp = new TankLogProxy(ttp); //把时间放进log中
Moveable m = tlp;
m.move();
}
}
(5)打印结果
(6)聚合实现代理原理