責任鏈模式(Chain of Responsibility)的目標是使多個對象都有機會處理請求
在處理用戶的請求時可能要根據不同的情況對請求添加不同的處理邏輯
現在我們的需求是處理用戶的請求
首先建立用戶的請求和接收對象Request和Response
package com
public class Request {
String requestStr;
public String getRequestStr() {
return requestStr;
}
public void setRequestStr(String requestStr) {
this
}
}
package com
public class Response {
String responseStr;
public String getResponseStr() {
return responseStr;
}
public void setResponseStr(String responseStr) {
this
}
}
我們將處理用戶信息的邏輯抽象成為一個個的過濾器
package com
public interface Filter {
public void doFilter(Request request
}
注意在Filte接口中doFilter方法參數中有FilterChain的一個變量
package com
import java
import java
public class FilterChain implements Filter {
List<Filter> filters = new ArrayList<Filter>();
int index =
public FilterChain addFilter(Filter f) {
this
return this;
}
@Override
public void doFilter(Request request
if (index == filters
return;
Filter f = filters
index++;
f
}
}
在FilterChain中繼承了Filter接口
下面我們編寫三個過濾器
HTMLFilter類
package com
/**
* 過濾HTML中的腳本元素
* @author lcq
*
*/
public class HTMLFilter implements Filter {
@Override
public void doFilter(Request request
request
chain
response
}
}
SesitiveFilter類
package com
public class SesitiveFilter implements Filter {
@Override
public void doFilter(Request request
request
chain
response
}
}
FaceFilter類
package com
public class FaceFilter implements Filter {
@Override
public void doFilter(Request request
request
chain
response
}
}
最後編寫測試類
package com
public class Main {
public static void main(String[] args) {
String message =
Request request = new Request();
request
Response response = new Response();
response
FilterChain fc = new FilterChain();
fc
FilterChain fc
fc
fc
fc
System
System
}
}
在上面的實例中應該注意兩個地方
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27381.html