静态代理是在编译时就将接口, 实现类, 代理类一股脑儿全部手动完成, 但如果我们需要很多的代理, 每一个都这么手动的去创建实属浪费时间, 而且会有大量的重复代码 .
例如:
- // 声明一个接口
- package com.ceshi.proxy;
- public interface Moveable {
- // 提供一个 move 方法
- void move();}
- package com.ceshi.proxy;
- import java.util.Random;
- // 写一个实现类实现这个接口
- public class Tank implements Moveable {
- @Override
- public void move() {
- System.out.println("Tank Moving...");
- try {
- Thread.sleep(new Random().nextInt(10000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- package com.ceshi.proxy;
- // 再写一个 tank 的时间代理类实现 Moveable 接口
- public class TankTimeProxy implements Moveable {
- public TankTimeProxy(Moveable t) {
- super();
- this.t = t;
- }
- Moveable t;
- @Override
- public void move() {
- // 在执行 move 方法前后加上有关时间的代码逻辑, 以此来实现类似日志管理
- long start = System.currentTimeMillis();
- System.out.println("starttime:" + start);
- t.move();
- long end = System.currentTimeMillis();
- System.out.println("time:" + (end-start));
- }
- }
来源: http://www.bubuko.com/infodetail-2612754.html