设计模式—责任链模式
责任链将处理请求在链条的节点上传递,每到一个节点可被处理或者也可不被处理。
典型的是在servlet中过滤器filter的的处理方式。当request请求或者response请求时,请求经过过滤链上的节点后,又进入下一个节点,直到链尾。
下面以模仿servlet中filter的处理方式(马士兵老师设计模式讲解内容):
1.过滤器接口
package com.bjsxt.dp.filter;
public interface Filter {
void doFilter(Request request, Response response, FilterChain chain);
}
2.过滤器链
package com.bjsxt.dp.filter;
import java.util.ArrayList;
import java.util.List;
public class FilterChain implements Filter {
List<Filter> filters = new ArrayList<Filter>();
int index = 0;
public FilterChain addFilter(Filter f) {
this.filters.add(f);
return this;
}
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
if(index == filters.size()) return ;
Filter f = filters.get(index);
index ++;
f.doFilter(request, response, chain);
}
}
3.过滤链_1
package com.bjsxt.dp.filter;
public class HTMLFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
//process the html tag <>
request.requestStr = request.requestStr.replace('<', '[')
.replace('>', ']') + "---HTMLFilter()";
chain.doFilter(request, response, chain);
response.responseStr += "---HTMLFilter()";
}
}
4.过滤器_2
package com.bjsxt.dp.filter;
public class SesitiveFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
request.requestStr = request.requestStr.replace("被就业", "就业")
.replace("敏感", "") + "---SesitiveFilter()";
chain.doFilter(request, response, chain);
response.responseStr += "---SesitiveFilter()";
}
}
5.request请求
package com.bjsxt.dp.filter;
public class Request {
String requestStr;
public String getRequestStr() {
return requestStr;
}
public void setRequestStr(String requestStr) {
this.requestStr = requestStr;
}
}
6.response请求
package com.bjsxt.dp.filter;
public class Response {
String responseStr;
public String getResponseStr() {
return responseStr;
}
public void setResponseStr(String responseStr) {
this.responseStr = responseStr;
}
}
7.客户端请求
package com.bjsxt.dp.filter;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
String msg = "大家好:),<script>,敏感,被就业,网络授课没感觉,因为看不见大家伙儿";
Request request = new Request();
request.setRequestStr(msg);
Response response = new Response();
response.setResponseStr("response");
FilterChain fc = new FilterChain();
fc.addFilter(new HTMLFilter())
.addFilter(new SesitiveFilter())
;
fc.doFilter(request, response, fc);
System.out.println(request.getRequestStr());
System.out.println(response.getResponseStr());
}
}
FilterChain中创建了一个过滤链,记录了有多少个过滤器,并且递归调用doFilter,经过一个过滤器后就走下一个过滤器,直到链尾。在递归返回的时候接着对response处理,处理的顺序和request
的顺序相反。
过滤链处理之后结果: