责任链或过滤器模式2-使用过滤链-马士兵设计模式教程 .

//过滤器接口
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]
	 */
}

原文(本文转自): http://blog.csdn.net/wxwzy738/article/details/7706643
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值