马士兵的filterchain练习一下,有点小改动
package filter;
import filterChain.FilterChain;
import information.Request;
import information.Response;
public interface Filter {
public void doFilter(Request rq, Response rp, FilterChain fc);
}
package filterChain;
import information.Request;
import information.Response;
import java.util.ArrayList;
import java.util.List;
import filter.Filter;
public class FilterChain implements Filter {
List<Filter> chain = new ArrayList<Filter>();
int i = 0;
public Filter addFilter(Filter f) {
chain.add(f);
return this;
}
public void doFilter(Request rq, Response rp){
doFilter(rq, rp, this);
}
public void doFilter(Request rq, Response rp, FilterChain fc) {
if (i == chain.size())
return;
Filter f = chain.get(i);
i++;
f.doFilter(rq, rp, fc);
}
}
package filter.impl;
import information.Request;
import information.Response;
import filter.Filter;
import filterChain.FilterChain;
public class TextFilter implements Filter {
public void doFilter(Request rq, Response rp, FilterChain fc) {
rq.setS(rq.getS().replace("fang", "方"));
fc.doFilter(rq, rp);
rp.setS(rp.getS()+"TextFilter ");
}
}
package filter.impl;
import information.Request;
import information.Response;
import filter.Filter;
import filterChain.FilterChain;
public class AddFilter implements Filter {
public void doFilter(Request rq, Response rp, FilterChain fc) {
rq.setS("姓名: "+rq.getS());
fc.doFilter(rq, rp);
rp.setS(rp.getS() + "AddFilter ");
}
}
package information;
public class Request {
String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
package information;
public class Response {
private String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
package test;
import filter.impl.AddFilter;
import filter.impl.TextFilter;
import filterChain.FilterChain;
import information.Request;
import information.Response;
public class Test {
public static void main(String[] args) {
Request rq = new Request();
Response rp = new Response();
TextFilter f = new TextFilter();
AddFilter af = new AddFilter();
FilterChain fc = new FilterChain();
rq.setS("fangshaowei");
rp.setS("返回信息: ");
fc.addFilter(f);
fc.addFilter(af);
fc.doFilter(rq, rp, fc);
System.out.println(rq.getS());
System.out.println(rp.getS());
}
}