定义:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
1.定义一个过滤器接口
2.定义多个过滤器,实现接口
3.定义一个过滤器责任链处理器,里面有一个过滤器类型的list,一个add方法,一个dofilter方法
class FilterChain implements Filter{ private List<Filter> filterList = new ArrayList<Filter>(); public FilterChain add(Filter filter){ filterList.add(filter); return this; } @Override public boolean doFilter(Msg msg) { for(Filter filter:filterList){ if(!filter.doFilter(msg)){ return false; } } return true; } }
4.使用:
Msg msg = new Msg(); msg.setMsg("***************************** "); FilterChain filterChain = new FilterChain(); filterChain.add(new HTMLFilter()).add(new SensitiveFilter()); FilterChain filterChain1 = new FilterChain(); filterChain1.add(new FaceFilter()).add(new URMFilter()); filterChain.add(filterChain1); filterChain.doFilter(msg); System.out.println(msg);