责任链(过滤器)模式
假设从客户端发送数据给服务端,接着服务端再将数据传输回客户端,同时需要将数据进⾏⼀些过滤,这时候就可以考虑过滤器模式。⾸先定义Request和Response,⾥⾯就封装⼀个String
public class Request {
String requestStr;
}
public class Response {
String responseStr;
}
定义⼀个Filter接⼝
public abstract interface MyFilter {
public abstract void doFilter(Request request,Response response,FilterChain fc);
replaceall()
}
使⽤进FilterChain⾏操作
public class FilterChain implements MyFilter{
ArrayList<MyFilter> myFilters;
int index;
public FilterChain() {
myFilters = new ArrayList<MyFilter>();
index=0;
}
public void add(MyFilter mf) {
myFilters.add(mf);
}
@Override
public void doFilter(Request request, Response response,FilterChain fc) {
if(index == fc.myFilters.size()) return;
MyFilter mf = (index);
index++;
mf.doFilter(request,response,fc);
}
}
写2个实现MyFilter的类(具体的拦截类HTMLTagFilter,SensitiveFilter)
public class HTMLTagFilter implements MyFilter{
@Override
public void doFilter(Request request,Response response,FilterChain fc) {
fc.doFilter(request, response, fc);
}
}
public class SensitiveFilter implements MyFilter{
@Override
public void doFilter(Request request,Response response,FilterChain fc) {
fc.doFilter(request, response, fc);
}
}
实现的原理就是,当第⼀个拦截完之后,由第⼀个去执⾏下⼀个,如此反复,当执⾏完之后,⼜会倒序执⾏。调⽤过程main函数:
public class Main {
public static void main(String[] args) {
String msg = "<a> 你好,敏感,被动,我艹,fuck";
Request request = new Request();
Response response = new Response();
//MyFilter[] filters ={new HTMLTagFilter(),new SensitiveFilter()};
FilterChain fc = new FilterChain();
fc.add(new HTMLTagFilter());
fc.add(new SensitiveFilter());
//MyProcessor myProcessor = new MyProcessor(msg);
//String result = myProcessor.process(msg,fc);
fc.doFilter(request, response,fc);
System.out.questStr);
System.out.sponseStr);
}
}
执⾏结果:
[a] 你好,不敏感,被动,我艹,fuck--HTMLTagFilter--SensitiveFilter
responseStr--SensitiveFilter--HTMLTagFilter

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。