我们有一个Car类,其中有一个行驶的方法实现了一个接口。
import java.util.Random;
public class Car implements Moveable {
@Override
public void move() {
// TODO Auto-generated method stub
try {
Thread.sleep(new Random().nextInt(1000));
System.out.println("汽车行驶中.....");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public interface Moveable {
public void move();
}
我们又有一个计时的类,并且实现了接口:
public class CarTimeProxy implements Moveable {
private Moveable m;
public CarTimeProxy(Moveable m) {
super();
this.m = m;
System.out.println("CarTimeProxy:"+m);
}
@Override
public void move() {
// TODO Auto-generated method stub
long starttime = System.currentTimeMillis();
System.out.println("汽车开始行驶.....");
m.move();
long endtime = System.currentTimeMillis();
System.out.println("汽车结束行驶.....时间为:" + (endtime - starttime) + "(毫秒)");
}
}
我们同样有一个记录日志的类,实现了行驶的接口:
public class CarLogProxy implements Moveable {
private Moveable m;
public CarLogProxy(Moveable m) {
super();
this.m = m;
System.out.println("CarLogProxy:m"+m);
}
@Override
public void move() {
// TODO Auto-generated method stub
System.out.println("日志开始.....");
m.move();
System.out.println("日志结束.....");
}
}
假设我们有这样一个需求:
想要先开始记录日志,然后开始计时,然后再开始行驶汽车
public class Client {
/*
* 测试类
*/
public static void main(String[] args) {
Car car = new Car();
CarTimeProxy ctp = new CarTimeProxy(car);
CarLogProxy clp = new CarLogProxy(ctp);
clp.move();
}
}
输出结果为:
日志开始.....
汽车开始行驶.....
汽车行驶中.....
汽车结束行驶.....时间为:565(毫秒)
日志结束.....
如果我们改变需求:先开始计时然后在开始记录日志,再行驶。那么我们可以这样修改:
public class Client {
/*
* 测试类
*/
public static void main(String[] args) {
Car car = new Car();
CarLogProxy clp = new CarLogProxy(car);
CarTimeProxy ctp = new CarTimeProxy(clp);
ctp.move();
}
}
输出结果为:
汽车开始行驶.....
日志开始.....
汽车行驶中.....
日志结束.....
汽车结束行驶.....时间为:321(毫秒)
我们可以仅仅做很少的修改,就实现了代码的变动