设计模式之责任链模式
???? 责任链模式(Chain of Responsibility)是Web项目中最经常用到的一个设计模式,比如是Apache Tomcat 的对Encoding的 处理,Struts2 的拦截器, jsp servlet 的Filter 等等,都是基于责任链模式设计的。比如有一个作业任务,先有一个对象对其负责处理,之后又交给其他的一个对象处理,一次传递下去,这是最通俗最简单的责任链模式的应用。
?
?
代码实例:(模拟jsp servlet 的Filter)
?
Filter:处理过滤信息的过滤接口类
package com.lyz.dp.filter;public interface Filter {void doFilter(Request request, Response response, FilterChain chain);}
?
?
FilterChain:责任链的核心类,执行链式调用 (实现Filter)
?
package com.lyz.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;}@Overridepublic void doFilter(Request request, Response response, FilterChain chain) {if(index == filters.size()) return ;Filter f = filters.get(index);index ++;f.doFilter(request, response, chain);}}
?
?
HTMLFilter:第一个过滤器 (实现Filter)
package com.lyz.dp.filter;public class HTMLFilter implements Filter {@Overridepublic 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()";}}
?
?
SesitiveFilter :第二个过滤器 (实现Filter)
?
package com.lyz.dp.filter;public class SesitiveFilter implements Filter {@Overridepublic void doFilter(Request request, Response response, FilterChain chain) {request.requestStr = request.requestStr.replace("被就业", "就业") .replace("敏感", "") + "---SesitiveFilter()";chain.doFilter(request, response, chain);response.responseStr += "---SesitiveFilter()";}}
?
Request:
?
package com.lyz.dp.filter;public class Request {String requestStr;public String getRequestStr() {return requestStr;}public void setRequestStr(String requestStr) {this.requestStr = requestStr;}}
?
Response:
?
package com.lyz.dp.filter;public class Response {String responseStr;public String getResponseStr() {return responseStr;}public void setResponseStr(String responseStr) {this.responseStr = responseStr;}}
?
?
测试类:
?
package com.lyz.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());}}
?
?
?
?
执行结果:
大家好:),[script],,就业---HTMLFilter()---SesitiveFilter()
response---SesitiveFilter()---HTMLFilter()
----------------------------------------------
执行过程:HTMLFilter()---SesitiveFilter()---SesitiveFilter()---HTMLFilter()
完成链式调用(栈式调用)先进后出。