设计模式之责任链模式
描述:责任链模式是一种对象的行为模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。
类图:
代码:
Filter过滤器
/** * 过滤器接口 * */ public interface Filter { public String doFilter(String msg); public Filter Next(); public void setFilter(Filter filter); }
HTML过滤器
public class HTMLFilter implements Filter { private Filter filter; @Override public String doFilter(String msg) { msg = msg.replace(" ", " "); return msg ; } @Override public Filter Next() { return filter; } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { this.filter = filter; } }
TAG过滤器
public class TagFilter implements Filter{ private Filter filter ; @Override public String doFilter(String msg) { msg = msg.replace("<", "["); msg = msg.replace(">", "]"); return msg; } @Override public Filter Next() { return filter; } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { this.filter = filter; } }
FilterChain过滤器链
public class FilterChain { private Filter filter ; public FilterChain(Filter _filter){ this.filter = _filter ; } public String doFilter(String msg){ // FIXME 仅支持单向过滤模式 while(null != filter){ msg = filter.doFilter(msg); filter = filter.Next() ; } return msg ; } }
调用者
public class Main { public static void main(String[] args){ Filter htmlFilter = new HTMLFilter(); Filter tagFilter = new TagFilter(); htmlFilter.setFilter(tagFilter) ; FilterChain chain = new FilterChain(htmlFilter) ; String msg = chain.doFilter("我是一个中国人。 <a>http://baidu.com</a>"); System.out.println(msg); } }
上述代码还只支持单向过滤,要支持双向过滤,可以参考tomcat的过滤器源码。