Chain of Responsibility
单向责任链
- 实体类
class Msg {
String name;
String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
- 基本Filter
interface Filter {
boolean filter(Msg m);
}
class HTMLFilter implements Filter {
public boolean filter(Msg m) {
String r = m.getMsg();
r = r.replace('<', '[');
r = r.replace('>', ']');
m.setMsg(r);
return true;
}
}
class CensorFilter implements Filter {
public boolean filter(Msg m) {
String r = m.getMsg();
r = r.replace("草", "*");
m.setMsg(r);
return false;
}
}
class EmotionFilter implements Filter {
public boolean filter(Msg m) {
String r = m.getMsg();
r = r.replace("微笑", ":)") ;
m.setMsg(r);
return true;
}
}
- 责任链
class FilterChain implements Filter{
List<Filter> filters = new ArrayList<>();
public FilterChain add(Filter f) {
filters.add(f);
return this;
}
public boolean filter(Msg m) {
for (Filter f : filters) {
if (!f.filter(m)) return false;
}
return true;
}
}
- Client
Msg msg = new Msg();
msg.setMsg("大家好, 微笑草, <script>");
FilterChain filters1 = new FilterChain();
filters1.add(new HTMLFilter())
.add(new CensorFilter());
FilterChain filters2 = new FilterChain();
filters2.add(new EmotionFilter());
filters1.add(filters2);
filters1.filter(msg);
System.out.println(msg);
由于CensorFilter返回false,所以只有前两个过滤器生效。
双向责任链
- 实体类
class Response {
String msg;
}
class Request {
String msg;
}
- 基本Filter
interface Filter {
void doFilter(Request request, Response response, FilterChain chain);
}
class AFilter implements Filter {
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("AFilter is filtering request..."); // do the business
// 如果不想继续传播就把下面一行注释了
chain.doFilter(request, response);
System.out.println("AFilter is filtering response..."); // do the business
}
}
class BFilter implements Filter {
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("BFilter is filtering request...");
chain.doFilter(request, response);
System.out.println("BFilter is filtering response...");
}
}
- FilterChain
class FilterChain {
public List<Filter> filters = new ArrayList<>();
private int i = 0;
public FilterChain addFilter(Filter f) {
filters.add(f);
return this;
}
public void doFilter(Request request, Response response) {
if (i == filters.size()) {
setFilterIndex(0);
} else {
filters.get(i).doFilter(request, response, setFilterIndex(i + 1));
}
}
private FilterChain setFilterIndex(int i) {
this.i = i;
return this;
}
}
- Client
FilterChain chain = new FilterChain();
chain.addFilter(new AFilter()).addFilter(new BFilter());
chain.doFilter(new Request(), new Response());