Chain of responsibility Pattern

责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。



Main

package com.dp.chainofresponsibility;

public class Main {
	public static void main(String[] args) {
		String msg = "hello:),敏感mingan大家好<h1>.";
		
		MsgProcessor mp = new MsgProcessor();
		mp.setMsg(msg);
		
		FilterChain fc1 = new FilterChain();
		fc1.addFilter(new HTMLFilter());
		FilterChain fc2 = new FilterChain();
		fc2.addFilter(new SensitiveFilter()).addFilter(new FaceFilter());
		
		fc1.addFilter(fc2);
		mp.setFc(fc1);
		String result = mp.process();
		System.out.println(result);
	}
}
/*
hello^v^,萌萌大家好(h1).
 */

MsgProcessor

package com.dp.chainofresponsibility;
/**
 * 信息处理
 * 信息和过滤器链
 * */
public class MsgProcessor {
	private String msg = null;
	//Filter[] filters = {new FaceFilter(),new HTMLFilter(),new SensitiveFilter()};//可扩展
	private FilterChain fc;

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	public FilterChain getFc() {
		return fc;
	}

	public void setFc(FilterChain fc) {
		this.fc = fc;
	}
	
	public String process() {
		String r = msg;
/*		for(Filter f:filters) {
			r = f.doFilter(r);
		}*/
		
		return fc.doFilter(msg);
	}

}

Filter

package com.dp.chainofresponsibility;
/**
 * 过滤器
 * */
public interface Filter {
	String doFilter(String str); 
}

FilterChain

package com.dp.chainofresponsibility;

import java.util.ArrayList;
import java.util.List;
/**
 * 过滤器链:一系列Filter
 * */
public class FilterChain implements Filter{
	
	List<Filter> filters = new ArrayList<Filter>();
	public FilterChain addFilter(Filter f) {
		this.filters.add(f);
		return this;
	}
	public String doFilter(String str) {
		String r = str;
		for(Filter f: filters) {
			r = f.doFilter(r);
		}
		return r;
	}

}

HTMLFilter

package com.dp.chainofresponsibility;

public class HTMLFilter implements Filter {

	public String doFilter(String str) {
		return str.replaceAll("<", "(").replaceAll(">",")");
	}

}

SensitiveFilter

package com.dp.chainofresponsibility;

public class SensitiveFilter implements Filter {

	public String doFilter(String str) {
		return str.replaceAll("敏感", "萌萌").replaceAll("mingan", "");
	}

}

FaceFilter

package com.dp.chainofresponsibility;

public class FaceFilter implements Filter {

	public String doFilter(String str) {
		return str.replace(":)","^v^");
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值