我试了一下,代理类不实现接口,用继承也行,那为什么要用接口呢?为什么呢?代码如下:
接口:
public interface Moveable {
void move();
}
真实类:
public class Tank implements Moveable {
public void move() {
System.out.println("Tank Moving...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} ?
}
}
代理类1:
public class TankExtends extends Tank {
Tank t;
public TankExtends(Tank t){
this.t = t;
}
public void move() {
long start = System.currentTimeMillis();
System.out.println("time:" + start);
t.move();
long end = System.currentTimeMillis();
System.out.println("time:" + end);
}
}
代理类2:
public class TankExtends2 extends Tank {
Tank t;
public TankExtends2(Tank t){
this.t = t;
}
public void move() {
System.out.println("start");
t.move();
System.out.println("exit");
}
}
运行类:
public class Client {
public static void main(String[] args) {
Tank t = new Tank();
Tank te2 = new TankExtends2(t);
Tank te = new TankExtends(te2);
te.move();
}
?
}
------解决方案--------------------
你extends Tank这一个类本身也实现了 那个接口,
并且你这二个类属于TANK的子类吧,
------解决方案--------------------
只能说基于接口编程,到后期维护更简单点需要改动的地方相对来说少一点
------解决方案--------------------
这跟java没关系,设于设计的范畴。我还以为是java的动态代理呢。