设计模式之责任链(Chain of Responsibility)模式

Java Web中的Filter(包括struts2中的过滤器)就是典型的责任链模式,看了以下的代码,就大概能知道Filter是怎么个实现的了:

public class Request {
String requestStr;

public String getRequestStr() {
return requestStr;
}

public void setRequestStr(String requestStr) {
this.requestStr = requestStr;
}
}

public class Response {
String responseStr;

public String getResponseStr() {
return responseStr;
}

public void setResponseStr(String responseStr) {
this.responseStr = responseStr;
}

}

public interface Filter {
void doFilter(Request request, Response response, FilterChain chain);
}

public class FilterChain implements Filter {
List<Filter> filters = new ArrayList<Filter>();
int index = 0;

[b][color=blue]public FilterChain addFilter(Filter f) {[/color][/b]
this.filters.add(f);
return this;
}

@Override
public void doFilter(Request request, Response response, FilterChain chain) {
if(index == filters.size()) return ;

Filter f = filters.get(index);
index ++;
f.doFilter(request, response, chain);
}
}

[color=blue]public class HTMLFilter implements Filter [/color]{


@Override
public void doFilter(Request request, Response response, FilterChain chain) {
//process the html tag <>
request.requestStr = request.requestStr.replace('<', '[')
.replace('>', ']') + "---HTMLFilter()";
chain.doFilter(request, response, chain);
response.responseStr += "---HTMLFilter()";
}

}

[color=blue]public class SesitiveFilter implements Filter {[/color]


@Override
public void doFilter(Request request, Response response, FilterChain chain) {
request.requestStr = request.requestStr.replace("被就业", "就业")
.replace("敏感", "") + "---SesitiveFilter()";
chain.doFilter(request, response, chain);
response.responseStr += "---SesitiveFilter()";

}

}

public class Main {

/**
* @param args
*/
public static void main(String[] args) {
String msg = "大家好:),<script>,敏感,被就业,网络授课没感觉,因为看不见大家伙儿";
Request request = new Request();
request.setRequestStr(msg);
Response response = new Response();
response.setResponseStr("response");
FilterChain fc = new FilterChain();
fc.addFilter(new HTMLFilter())
.addFilter(new SesitiveFilter())
;

fc.doFilter(request, response, fc);
System.out.println(request.getRequestStr());
System.out.println(response.getResponseStr());
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值