先创建一个接口Eatable
提供“吃“的方法
package test.proxy;
public interface Eatable {
void eat();
}
创建一个实现类,实现Eatable接口
package test.proxy;
public class Apple implements Eatable{
//实现一个“吃”的方法
@Override
public void eat() {
System.out.println("eatting ....");
try {
Thread.sleep(2000); //睡眠两秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
创建一个时间代理类,计算eat()方法执行的时间
package test.proxy;
//关于时间的代理
public class TimeProxy implements Eatable{
Eatable e;
public TimeProxy(Eatable e) {
super();
this.e = e;
}
@Override
//计算执行的方法的时间
public void eat() {
long l1 = System.currentTimeMillis();//获取开始时间
e.eat();
long l2 = System.currentTimeMillis();//获取结束时间
System.out.println(l2 - l1); //输出总的运行时间
}
}
创建一个日志代理类,提示开始和结束信息
package test.proxy;
//关于日志记录的代理
public class LogProxy implements Eatable{
Eatable e;
public LogProxy(Eatable e) {
super();
this.e = e;
}
@Override
public void eat() {
System.out.println("start。。。。。");
e.eat();
System.out.println("end 。。。。。。");
}
}
最后创建一个测试类
package test.proxy;
public class Test {
public static void main(String[] args) {
Eatable apple = new Apple();
//Eatable time = new TimeProxy(apple);
//Eatable log = new LogProxy(time);
//log.eat();
//output:
//start。。。。。
//eatting ....
//2001
//end 。。。。。。
Eatable log = new LogProxy(apple);
Eatable time = new TimeProxy(log);
time.eat();
//output
//start。。。。。
//eatting ....
//end 。。。。。。
//2000
//第一个输出结果和第二个输出结果的不同
//在于时间的输出顺序
}
}