责任链模式(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^");
}
}