Java设计模式之责任链模式-学习笔记1_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java设计模式之责任链模式-学习笔记1

Java设计模式之责任链模式-学习笔记1

 2014/5/25 1:09:30  wang吖  程序员俱乐部  我要评论(0)
  • 摘要:设计模式之责任链模式(ChainofResponsibility)是Web项目中最经常用到的一个设计模式,比如是ApacheTomcat的对Encoding的处理,Struts2的拦截器,jspservlet的Filter等等,都是基于责任链模式设计的。下面直接来模拟WEB发送一个请求Request经过两个过滤链HTMLFilter过滤标签、SensitiveFilter过滤敏感词汇,经过过滤之后返回一个Response对象实例代码:publicinterfaceFilter
  • 标签:笔记 学习 Java 责任 模式 设计 设计模式 学习笔记

设计模式责任链模式(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());
	}
}

?

上一篇: Android:启动引导页实现 下一篇: 没有下一篇了!
发表评论
用户名: 匿名