使用聚合的方式实现静态代理
生活随笔
收集整理的這篇文章主要介紹了
使用聚合的方式实现静态代理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
我們有一個Car類,其中有一個行駛的方法實現了一個接口。
import?java.util.Random; public?class?Car?implements?Moveable?{@Overridepublic?void?move()?{//?TODO?Auto-generated?method?stubtry?{Thread.sleep(new?Random().nextInt(1000));System.out.println("汽車行駛中.....");}?catch?(InterruptedException?e)?{//?TODO?Auto-generated?catch?blocke.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);}@Overridepublic?void?move()?{//?TODO?Auto-generated?method?stublong?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);}@Overridepublic?void?move()?{//?TODO?Auto-generated?method?stubSystem.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(毫秒)
日志結束.....
如果我們改變需求:先開始計時然后在開始記錄日志,再行駛。那么我們可以這樣修改:
輸出結果為:
汽車開始行駛.....
日志開始.....
汽車行駛中.....
日志結束.....
汽車結束行駛.....時間為:321(毫秒)
我們可以僅僅做很少的修改,就實現了代碼的變動
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的使用聚合的方式实现静态代理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何利用反射来绕过泛型
- 下一篇: JDK动态代理与CGLIB动态代理区别