動態代理和聚合代理的區別
public static void main(String[] args) {
Car car = new Car();
InvocationHandler h =new TimeHandler(car);
Class<?> cls = car.getClass();
Moveable m = (Moveable) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), h);
InvocationHandler h1 = new LogHandler(m);
Moveable m1 = (Moveable) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), h1);
m1.move();
Car2 car2 = new Car2();
InvocationHandler h2 =new TimeHandler(car2);
Class<?> cls2 = car2.getClass();
Moveable m2 = (Moveable) Proxy.newProxyInstance(cls2.getClassLoader(), cls2.getInterfaces(), h2);
InvocationHandler h3 = new LogHandler(m2);
Moveable m3 = (Moveable) Proxy.newProxyInstance(cls2.getClassLoader(), cls2.getInterfaces(), h3);
m3.move();
}
Car 的部分 實現了 日志的記錄,時間的記錄,?
Car2 的部分 代表其他車輛也可以使用 同樣的代理類,
也就是說,我再定義一個火車也是可以用同樣的日志代理和時間代理類的。
而聚合代理就不能完成了對吧。我這樣理解對嘛?老師們
2016-08-21
聚合代理也能完成,聚合方式產生的代理比繼承方式更好!所以聚合代理一樣可以用同樣的日志代理和時間代理類的,具體的可以搜索相關視頻哦