//过滤器接口
public interface Filter {
public String doFilter(String str);
}
//HTML的过滤器
public class HTMLFilter implements Filter{
@Override
public String doFilter(String str) {
if(str==null)return "";
str=str.replace("<", "[");
str=str.replace(">", "]");
return str;
}
}
//敏感词的过滤器
public class SensitiveFilter implements Filter{
@Override
public String doFilter(String str) {
if(str==null)return "";
str=str.replace("敏感", "mingan");
return str;
}
}
//过滤链,把要使用的过滤器放在集合当中进行依次处理
public class FilterChain implements Filter{
private List<Filter> list=new ArrayList<Filter>();
public FilterChain addfilter(Filter filter){
list.add(filter);
return this;
}
public String doFilter(String str){
System.out.println("#################");
if(str==null)return "";
for(Filter filter : list){
str=filter.doFilter(str);
}
return str;
}
}
//字符串过滤的处理类
public class Process {
private String str;
private FilterChain filterchain;
//字符串过滤的处理方法
public String process(){
if(filterchain==null) return str;
//使用在client类中添加的过滤器在过滤链进行处理
return filterchain.doFilter(str);
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public FilterChain getFilterchain() {
return filterchain;
}
public void setFilterchain(FilterChain filterchain) {
this.filterchain = filterchain;
}
}
public class Client {
public static void main(String[] args) {
String str="这是我的一个敏感链接<a>优酷</a>";
FilterChain fc=new FilterChain();
// fc.addfilter(new HTMLFilter()).addfilter(new SensitiveFilter());
fc.addfilter(new HTMLFilter());
FilterChain fc1=new FilterChain();
fc1.addfilter(new SensitiveFilter());
fc.addfilter(fc1);//在一个过滤链上面再加上一个过滤链
Process pro=new Process();
pro.setStr(str);
pro.setFilterchain(fc);
str=pro.process();
System.out.println(str);
}
/**
* 运行结果:
* #################
* #################
* 这是我的一个mingan链接[a]优酷[/a]
*/
}