什麼是責任鏈模式:
將請求同一類資源的請求對象練成一條鏈,所提交的請求到某一個鏈節,如果該鏈節能處理則不必要往下傳,不然則繼續傳到下一個對象鏈接去處理。
開發中常見的場景:
1.springmvc的攔截器
2.java中,異常處理機制,拋出異常
3.javascript的事件冒泡機制
責任鏈例子:
這裏的場景是實現一個攔截器demo,所限當然是定義我們的攔截器,然後,使用時,就繼承它
/**
* 定義一個攔截器
* @author liuxg
* @date 2016年5月27日 下午6:01:27
*/
public abstract class Interceptor {
protected Interceptor nextChain ;
public void setNextChain(Interceptor nextChain) {
this.nextChain = nextChain;
}
public abstract void beginIntecept(String condition);
}
class Interceptor1 extends Interceptor{
@Override
public void beginIntecept(String condition) {
if ("interceptor1".equals(condition)) {
System.out.println("攔截器到interceptor1");
}else{
System.out.println("interceptor1無法處理,到下一個攔截器");
nextChain.beginIntecept(condition);
}
}
}
class Interceptor2 extends Interceptor{
@Override
public void beginIntecept(String condition) {
if ("interceptor2".equals(condition)) {
System.out.println("攔截器到interceptor2");
}else{
System.out.println("interceptor2無法處理,到下一個攔截器");
nextChain.beginIntecept(condition);
}
}
}
class Interceptor3 extends Interceptor{
@Override
public void beginIntecept(String condition) {
if ("interceptor3".equals(condition)) {
System.out.println("攔截器到interceptor3");
}else{
System.out.println("interceptor3無法處理,到下一個攔截器");
nextChain.beginIntecept(condition);
}
}
}
客戶端可以傳遞一個條件字符串,所有跟其中一個攔截器匹配,則該攔截器處理,如果不行,則傳遞到下一個攔截器處理
public class Client {
public static void main(String[] args) {
Interceptor interceptor1 = new Interceptor1();
Interceptor interceptor2 = new Interceptor2();
Interceptor interceptor3 = new Interceptor3();
interceptor1.setNextChain(interceptor2);
interceptor2.setNextChain(interceptor3);
interceptor1.beginIntecept("interceptor3");//處理條件
}
}