参考:https://blog.csdn.net/weixin_48052161/article/details/118230819
责任链模式的典型就是过滤器模式:
而过滤器模式里的过滤器又使用了策略模式和装饰器模式;
过滤器和过滤链形成相互的聚合关系;
过滤器需要添加到过滤链中形成聚合关系;
而过滤链在使用时,要把自己传递给过滤器使用,进行下一过滤!
代码演示如下:
自定义的request和response:
package com.example.dtest.design23.filter;
public class Request {
String str;
}
package com.example.dtest.design23.filter;
public class Response {
String str;
}
Filter(过滤器接口):
package com.example.dtest.design23.filter;
public interface Filter {
void doFilter(Request request,Response response,FilterChain chain);
}
过滤链:
package com.example.dtest.design23.filter;
import java.util.ArrayList;
import java.util.List;
public class FilterChain {
List<Filter> filters = new ArrayList<>();
int index = 0;
public FilterChain add(Filter f){
filters.add(f);
return this;
}
public void doFilter(Request request,Response response){
if(index == filters.size()){
return;
}
Filter filter = filters.get(index);
index++;
filter.doFilter(request, response, this);
}
}
HTMLFilter过滤器实现类:
package com.example.dtest.design23.filter;
public class HTMLFilter implements Filter{
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
request.str = request.str.replaceAll("<","[").replaceAll(">","]") + "HTMLFilter()";
chain.doFilter(request, response);
response.str += "--HTMLFilter()";
}
}
SensitiveFilter过滤器实现类2:
package com.example.dtest.design23.filter;
public class SensitiveFilter implements Filter{
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
request.str = request.str.replaceAll("996", "955") + "SensitiveFilter()";
chain.doFilter(request, response);
response.str += "--SensitiveFilter()";
}
}
测试类:
package com.example.dtest.design23.filter;
public class FilterTest {
public static void main(String[] args) {
Request request = new Request();
request.str = "<<<<<<<<<<996大家好:),<script>,996欢迎访问 mashibing.com ,大家都是996 >>>>>>>>>>>>>>>";
Response response = new Response();
response.str = "response";
FilterChain chain = new FilterChain();
chain.add(new HTMLFilter()).add(new SensitiveFilter());
chain.doFilter(request, response);
System.out.println(request.str);
System.out.println(response.str);
}
}