本篇文章為大家展示了如何在Java中應(yīng)用責(zé)任鏈模式,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
成都創(chuàng)新互聯(lián)公司是一家專(zhuān)注于成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站與策劃設(shè)計(jì),東遼網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)公司做網(wǎng)站,專(zhuān)注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專(zhuān)業(yè)建站公司;建站業(yè)務(wù)涵蓋:東遼等地區(qū)。東遼做網(wǎng)站價(jià)格咨詢(xún):028-86922220
定義下面的攔截器接口:
/** * @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類(lèi),測(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)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。