设计模式总结-责任链模式.doc:..注:文档内容基本上来自于网上,并加上自己的理解而成。有的觉得网友总结得非常好,就主全照搬下来,供学习之用。然而,有的摘抄并没有加上原链接和出Filterchain例子(本例子模拟回路式的一个链式处理,要求输入按1,2,3这样的处理,而输出则再次需要以3f2,1的方式处理):publicinterfaceIFilter{publicvoiddoFilter(RequestrequestResponserespons巳FilterChainchain);}lassHTMLFilterimplementsIFilter{***@OverridepublicvoiddoFilter(Requestrequest,ResponseresponsezFilterChainchain){StringrequestStr=().replaceAII("<",T).replaceAII(">","]")+"…HTMLFilter";(requestStr);(request,response);StringresponseStr=().replaceAII(H\\"<").replaceAII("\\]"z">")+ -HTMLFilter";(responseStr);}}lassSensitiveFilterimplementsIFilter{***@OverridepublicvoiddoFilter(Requestrequest,Responseresponse,FilterChainchain){//TODOAuto-^”six”)+H—SensitiveFilter");(request,response);(().replaceAII("six,,/"seexxx'1+SensitiveFilter"));lassFilterChain{publicList<IFilter>filterChain=newArrayList<IFilter>();publicintcount=0;publicvoidaddFilter(IFilterfilter){(filter);publicvoiddoFilter(Requestrequest,Responseresponse){if(count>=)return;(count++).doFilter(request/response,this);}}测试代码:publicstaticvoidmain(Stringargs[]){Stringstr=n<Hl>,<H2>.Thisisasexfilm!";Stringstr2="[Haa]Thisisasixfilm!";Requestrequest二newRequest();(str);Responseresponse=newResponse();(str2);FilterChainchain=newFilterChain();(newHTMLFilterO);(newSensitiveFilter());(request,response);("Requeststr:+());("Responsestr:M+());}输出:Requeststr:[Hl],[H2].Thisisasixfilm!—HTMLFilter—-SensitiveFilterResponsestr:<Haa>Thisisaseexxx—SensitiveFilterfilm!——HTMLFilter注:链式处理有时候也叫做拦截器处理,其原理差不多。注意上面代码中如何实现对response以处理request刚好相反的次序处理的巧妙方法。httD:/
设计模式总结-责任链模式 来自淘豆网m.daumloan.com转载请标明出处.