责任链模式

最近由于项目处理的业务原因,想到了用责任链模式,平时做项目用的其他设计模式也不做。对设计模式也没有很深入的了解。责任链模式和filter差不多。就像servletfilter一样的。里面有个过滤链,来把所有的过滤器连在一起。然后一个一个的过滤请求。记得马士兵讲过一个责任链的例子。通俗易懂啊。

package com.bjsxt.dp.filter;

public interface Filter {
void doFilter(Request request, Response response, FilterChain chain);
}

package com.bjsxt.dp.filter;

public class Request {
String requestStr;

public String getRequestStr() {
return requestStr;
}

public void setRequestStr(String requestStr) {
this.requestStr = requestStr;
}
}

package com.bjsxt.dp.filter;

public class Response {

String responseStr;

public String getResponseStr() {

return responseStr;

}

public void setResponseStr(String responseStr) {

this.responseStr = responseStr;

}

}

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()";

}

}

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()";

}

}

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);

}

}

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());

}

}

<!--EndFragment-->

你可能感兴趣的:(责任链模式)