您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何在Java中應(yīng)用責(zé)任鏈模式,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
定義下面的攔截器接口:
/** * @Auther: haozz * @Date: 2018/5/27 22:15 * @Description:攔截器接口 **/ public interface Interceptor { boolean before(Object proxy, Object target, Method method,Object[] args); void around(Object proxy,Object target,Method method,Object[] args); void after(Object proxy,Object target,Method method,Object[] args); }
再定義3個(gè)攔截器:
/** * @Auther: haozz * @Date: 2018/5/27 22:19 * @Description:攔截器1 **/ public class Interceptor1 implements Interceptor{ @Override public boolean before(Object proxy, Object target, Method method, Object[] args) { System.out.print("[攔截器1]的before方法"); return true; } @Override public void around(Object proxy, Object target, Method method, Object[] args) { } @Override public void after(Object proxy, Object target, Method method, Object[] args) { System.out.print("[攔截器1]的after方法"); } }
/** * @Auther: haozz * @Date: 2018/5/27 22:19 * @Description:攔截器2 **/ public class Interceptor2 implements Interceptor{ @Override public boolean before(Object proxy, Object target, Method method, Object[] args) { System.out.print("[攔截器2]的before方法"); return true; } @Override public void around(Object proxy, Object target, Method method, Object[] args) { } @Override public void after(Object proxy, Object target, Method method, Object[] args) { System.out.print("[攔截器2]的after方法"); } }
/** * @Auther: haozz * @Date: 2018/5/27 22:19 * @Description:攔截器3 **/ public class Interceptor3 implements Interceptor{ @Override public boolean before(Object proxy, Object target, Method method, Object[] args) { System.out.print("[攔截器3]的before方法"); return true; } @Override public void around(Object proxy, Object target, Method method, Object[] args) { } @Override public void after(Object proxy, Object target, Method method, Object[] args) { System.out.print("[攔截器3]的after方法"); } }
我們使用上一篇(Java動(dòng)態(tài)代理之?dāng)r截器的應(yīng)用)中用到的InterceptorJdkProxy類,測(cè)試一下這段代碼。如下:
@Test public void MyTest(){ HelloWorld proxy1 = (HelloWorld) InterceptorJdkProxy.bind(new HelloWorldImpl(),"com.csdn.blog.impl.Interceptor1"); HelloWorld proxy2 = (HelloWorld) InterceptorJdkProxy.bind(proxy1,"com.csdn.blog.impl.Interceptor2"); HelloWorld proxy3 = (HelloWorld) InterceptorJdkProxy.bind(proxy2,"com.csdn.blog.impl.Interceptor3"); proxy3.sayHelloWorld(); }
運(yùn)行這段diamante后得到這樣的結(jié)果,請(qǐng)注意觀察其方法的執(zhí)行順序:
[攔截器3]的before方法
[攔截器2]的before方法
[攔截器1]的before方法
Hello World
[攔截器1]的after方法
[攔截器2]的after方法
[攔截器3]的after方法
上述內(nèi)容就是如何在Java中應(yīng)用責(zé)任鏈模式,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。