Java責(zé)任鏈模式模板代碼分享
更新時間:2018年01月12日 08:47:08 作者:dean_deng
這篇文章主要介紹了Java責(zé)任鏈模式模板代碼分享,具有一定借鑒價值,需要的朋友可以參考下
本文分享了一則Java編程責(zé)任鏈模式的模板代碼,代碼中有詳細(xì)注釋,大家可以參考。具體如下:
//抽象處理者 public abstract class Handler{ private Handler nextHandler; //每個處理者都必須對請求做出處理 public final Response handleMessage(Request request){ Response response = null; //判斷是否自己的處理級別 if(this.getHandlerLevel().equals(request.getRequestLevel())){ response = this.echo(request); }else{ //判斷是否有下一個處理者 if(this.nextHandler != null){ response = this.nextHandler.handleMessage(request); }else{ //沒有適當(dāng)?shù)奶幚碚? } } return response; } //設(shè)置下一個處理者是誰 public void setNext(Handler _handler){ this.nextHandler = _handler; } //每個處理者都有一個處理級別 protected abstract Level getHandlerLevel(); //每個處理者都必須實(shí)現(xiàn)處理任務(wù) protected abstract Response echo(Request request); } //具體處理者1 publlic class ConcreteHandler1 extends Handler{ //定義自己的處理邏輯 protected Response echo(Request request){ //完成處理邏輯 return null; } //設(shè)置自己的處理級別 protected Level getHandlerLevel(){ //設(shè)置自己的處理級別 return null; } } //具體處理者2 publlic class ConcreteHandler2 extends Handler{ //定義自己的處理邏輯 protected Response echo(Request request){ //完成處理邏輯 return null; } //設(shè)置自己的處理級別 protected Level getHandlerLevel(){ //設(shè)置自己的處理級別 return null; } } //具體處理者3 publlic class ConcreteHandler3 extends Handler{ //定義自己的處理邏輯 protected Response echo(Request request){ //完成處理邏輯 return null; } //設(shè)置自己的處理級別 protected Level getHandlerLevel(){ //設(shè)置自己的處理級別 return null; } } //模式中有關(guān)框架的代碼 public class Level{ //定義一個請求和處理等級 } public class Request{ //請求的等級 public Level getRequestLevel(){ return null; } } public class Response{ //處理返回者的數(shù)據(jù) } //場景類 public class Client{ public static void main(String[] args){ //聲明所有的處理節(jié)點(diǎn) Handler handler1 = new ConcreteHandler1(); Handler handler2 = new ConcreteHandler2(); Handler handler2 = new ConcreteHandler3(); //設(shè)置鏈中的階段順序1-->2-->3 handler1.setNext(handler2); handler2.setNext(handler3); //提交請求 Response response = handler.handleMessage(new Request()); } }
總結(jié)
以上就是本文關(guān)于Java責(zé)任鏈模式模板代碼分享的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
Springsecurity Oauth2如何設(shè)置token的過期時間
如果用戶在指定的時間內(nèi)有操作就給token延長有限期,否則到期后自動過期,如何設(shè)置token的過期時間,本文就來詳細(xì)的介紹一下2021-08-08SpringBoot 多任務(wù)并行+線程池處理的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot 多任務(wù)并行+線程池處理的實(shí)現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04spring5 SAXParseException:cvc-elt.1: 找不到元素“beans 的聲明詳解
這篇文章主要給大家介紹了關(guān)于spring5 SAXParseException:cvc-elt.1: 找不到元素“beans 聲明的相關(guān)資料,需要的朋友可以參考下2020-08-08詳解SpringCloud Gateway之過濾器GatewayFilter
這篇文章主要介紹了詳解SpringCloud Gateway之過濾器GatewayFilter,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10