本文主要是介绍责任链模式-Chain of Responsibility,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
主要解决:职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了。
//Filter实现
public class Servlet_Main {public static void main(String[] args) {Request request = new Request();request.str = "大家好:),<script>,欢迎访问 mashibing.com ,大家都是996 ";Response response = new Response();response.str = "response";FilterChain chain = new FilterChain();chain.add(new HTMLFilter()).add(new SensitiveFilter());chain.doFilter(request, response);System.out.println(request.str);System.out.println(response.str);}
}interface Filter {void doFilter(Request request, Response response, FilterChain chain);
}class HTMLFilter implements Filter {@Overridepublic void doFilter(Request request, Response response, FilterChain chain) {request.str = request.str.replaceAll("<", "[").replaceAll(">", "]") + "HTMLFilter()";chain.doFilter(request, response);response.str += "--HTMLFilter()";}
}class Request {String str;
}class Response {String str;
}class SensitiveFilter implements Filter {@Overridepublic void doFilter(Request request, Response response, FilterChain chain) {request.str = request.str.replaceAll("996", "955") + " SensitiveFilter()";chain.doFilter(request, response);response.str += "--SensitiveFilter()";}
}class FilterChain {List<Filter> filters = new ArrayList<>();int index = 0;public FilterChain add(Filter f) {filters.add(f);return this;}public void doFilter(Request request, Response response) {if(index == filters.size()) return;Filter f = filters.get(index);index ++;f.doFilter(request, response, this);}
}
这篇关于责任链模式-Chain of Responsibility的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!