设计模式之责任链模式(chain of responsiblility)

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

责任链模式(Chain of Responsibility)是一种处理请求的模式,它让多个处理器都有机会处理该请求,直到其中某个处理成功为止。责任链模式把多个处理器串成链,然后让请求在链上传递;

Java 设计模式之责任链模式(chain of responsiblility)

  • 定义Request, http 请求对象
public class MyRequest {
	private String body;
	public MyRequest(String body)
	{
		this.body = body;
	}
	public String getBody()
	{
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}
}
  • 定义Response, http 响应对象
public class MyResponse {
	private String body;
	public MyResponse(String body)
	{
		this.body = body;
	}
	public String getBody()
	{
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}
}
  • 定义过虑器接口
public interface MyFilter {
	 public void doFilter(MyRequest request, MyResponse response, MyFilterChain filterChain);
}

定义公共过滤器接口,任何想加入这个过虑器,都必须实现这个接口,以方便整个过程的调用!

  • 定义敏感过虑器
public class SensitiveFilter implements MyFilter{
	public void doFilter(MyRequest request, MyResponse response, MyFilterChain filterChain) {
		String body = request.getBody().replace("敏感", "#pangugle#");
		request.setBody(body);

		filterChain.doFilter(request, response, filterChain);
		response.setBody(body + "==============正常了");
	}
}

实现了一个敏感词过虑器,在这个过虑器之后,任何有敏感的词都被替换成了 #pangugle# ;

  • 定义过滤器管理器
public class MyFilterChain implements MyFilter{
	 private List<MyFilter> mFilters = new ArrayList<MyFilter>();
	 private int currentIndex = 0;

	 public MyFilterChain addFilter(MyFilter filter)
	 {
		 mFilters.add(filter);
		 return this;
	 }

	@Override
	public void doFilter(MyRequest request, MyResponse response, MyFilterChain filterChain) {
		if(currentIndex >= mFilters.size())
		{
			return;
		}

		MyFilter filter = mFilters.get(currentIndex ++);
		filter.doFilter(request, response, filterChain);
	}
}

所有过虑器都集中在这里统一管理!所有的过滤器合在一起成了一条链!

  • 测试类
public class App {
	public static void main(String[] args)
	{
		MyFilterChain filterChain = new MyFilterChain();
		filterChain.addFilter(new SensitiveFilter());

		MyRequest request = new MyRequest("敏感");
		MyResponse response = new MyResponse("=======");

		filterChain.doFilter(request, response, filterChain);

		LogHelper.log("request => " + request.getBody());
		LogHelper.log("response => " + response.getBody());
	}
}

现在,我们就可以在客户端组装出责任链,然后用责任链来处理请求;

运行结果为

【www.pangugle.com】-  request => #pangugle#
【www.pangugle.com】-  response => #pangugle#==============正常了