设计模式之责任链模式(Chain of Responsibility)是Web项目中最经常用到的一个设计模式,比如是Apache Tomcat 的对Encoding的 处理,Struts2 的拦截器, jsp servlet 的Filter 等等,都是基于责任链模式设计的。
?
下面直接来模拟WEB发送一个请求Request经过两个过滤链HTMLFilter过滤标签、SensitiveFilter过滤敏感词汇,经过过滤之后返回一个Response对象
?
实例代码:
class="java" name="code">public interface Filter { public void doFilter(Request req, Response rsp, FilterChain chain); } public class HTMLFilter implements Filter { @Override public void doFilter(Request req, Response rsp, FilterChain f) { req.request = req.request.replace("<html>", "[html]") + "---HTMLFilter()"; f.doFilter(req, rsp, f); rsp.response += "---HTMLFilter()"; } } public class SensitiveFilter implements Filter { @Override public void doFilter(Request req, Response rsp, FilterChain f) { req.request = req.request.replace("很黄很暴力", "很xxx很xxx") + "---SensitiveFilter()"; f.doFilter(req, rsp, f); rsp.response += "---SensitiveFilter()"; } } public class FilterChain implements Filter { private List<Filter> list = new ArrayList<Filter>(); private int index; @Override public void doFilter(Request req, Response rsp, FilterChain chain) { if (index == list.size()) { return; } Filter f = list.get(index); index++; f.doFilter(req, rsp, chain); } public FilterChain addFilter(Filter f) { list.add(f); return this; } } public class Request { String request = ""; public String getRequest() { return request; } public void setRequest(String request) { this.request = request; } } public class Response { String response = ""; public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } } public class Main { public static void main(String[] args) { String msg = "<html>很黄很暴力,天天开心"; Request request = new Request(); request.setRequest(msg); Response response = new Response(); // FilterChain ch = new FilterChain(); // ch.addFilter(new HTMLFilter()).addFilter(new SensitiveFilter()); FilterChain ch = new FilterChain(); ch.addFilter(new HTMLFilter()); FilterChain ch2 = new FilterChain(); ch2.addFilter(new SensitiveFilter()); ch.addFilter(ch2);// 过滤链上加过滤链 ch.doFilter(request, response, ch); System.out.println(request.getRequest()); System.out.println(response.getResponse()); } }
?