介紹
Java責(zé)任鏈(Chain of Responsibility)設(shè)計(jì)模式是指很多處理對象構(gòu)成一個(gè)鏈,鏈中前一個(gè)對象指向后一個(gè)對象。請求在鏈中傳遞,一個(gè)請求可以被一個(gè)或者多個(gè)對象處理。調(diào)用方(即客戶端)不知道請求會被鏈中的哪個(gè)對象處理,所以責(zé)任鏈模式可以方便組織責(zé)任鏈而不影響調(diào)用方。
責(zé)任鏈模式一般定義抽象類或者接口來規(guī)范行為,而定義具體類實(shí)現(xiàn)具體的處理邏輯。
示例
示例1:Netty中的handler就構(gòu)成了責(zé)任鏈模式
注:下面圖拷貝自Netty的ChannelPipeline API中的圖文章來源:http://www.zghlxwxcb.cn/news/detail-573473.html
示例2:一個(gè)簡單的責(zé)任鏈模式代碼示例
package com.thb;
// 定義一個(gè)抽象類,規(guī)范行為
public abstract class AbstractHandler {
private AbstractHandler nextHandler; // 指向下一個(gè)處理器
private char startWith;
public AbstractHandler(char startWith) {
this.startWith = startWith;
}
// 處理邏輯的抽象方法
public abstract void handleMessage(String msg);
// 設(shè)置下一個(gè)處理器
public void setNextHandler(AbstractHandler nextHandler) {
this.nextHandler = nextHandler;
}
// 取出下一個(gè)處理器
public AbstractHandler getNextHandler() {
return this.nextHandler;
}
}
// 定義具體類,實(shí)現(xiàn)真正的處理邏輯
package com.thb;
public class Handler extends AbstractHandler {
public Handler(char startWith) {
super(startWith);
}
@Override
public void handleMessage(String msg) {
// 具體處理邏輯
if (msg.startsWith("H")) {
System.out.println("process the message");
} else {
if (getNextHandler() != null) {
getNextHandler().handleMessage(msg);
} else {
System.out.println("no suitable hander");
}
}
}
}
// 定義一個(gè)客戶端來模擬調(diào)用
package com.thb;
public class Test2 {
public static void main(String[] args) {
AbstractHandler handler1 = new Handler('a');
AbstractHandler handler2 = new Handler('H');
AbstractHandler handler3 = new Handler('c');
handler1.setNextHandler(handler2);
handler2.setNextHandler(handler3);
String msg = "Hello";
handler1.handleMessage(msg);
msg = "world";
handler1.handleMessage(msg);
}
}
輸出結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-573473.html
到了這里,關(guān)于Java設(shè)計(jì)模式-責(zé)任鏈(Chain of Responsibility)模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!