責任鏈模式(Chain of Responsibility)能夠說是一個很是很是經常使用的模式,開源框架、 tomcat、jetty、mina 等裏面處處都是。java
最初學習這個模式的時候,各類版本的都有,反正設計模式也只是給出了一個抽象的表達,並沒說怎麼寫纔是對的,只要把思想表達出來就能夠了,未必要把本身框死在某個範圍裏面。設計模式
可是呢,在看開源框架的時候,發現牛人們彷佛都喜歡用同一種寫法來表達這個模式,因此也就細細的思考了一會,雖說不出來一個因此然來,但仍是以爲牛人們的寫法就是好,因此就寫了這篇文章。tomcat
如下是責任鏈模式的開源代碼裏面的最多見的版本。框架
package design.filter.filter3; /** * 過濾器接口 * @author li * */ public interface Filter { void doFilter(Request req, Response res, FilterChain chain); }
package design.filter.filter3; /** * 過濾器鏈 * @author li * */ public interface FilterChain { void invokeNext(Request req, Response res); }
package design.filter.filter3; public class Request { }
package design.filter.filter3; public class Response { }
package design.filter.filter3; import java.util.Vector; /** * 過濾器支持類 * @author li * */ public class FilterSuport { private Vector<Filter> filters = new Vector<Filter>(); public FilterSuport addFilter(Filter f) { filters.add(f); return this; } public void invoke(Request req, Response res) { new FilterChainSupport().invokeNext(req, res); } /** * 過濾器鏈表支持類 * @author li * */ private class FilterChainSupport implements FilterChain { int index = -1; @Override public void invokeNext(Request req, Response res) { if (++index < filters.size()) { filters.get(index).doFilter(req, res, this); } else { return; } } } }
package design.filter.filter3;
//測試 public class Test { public static void main(String[] args) { Request req = new Request(); Response res = new Response(); FilterSuport chain = new FilterSuport(); chain.addFilter(new Filter() { public void doFilter(Request req, Response res, FilterChain chain) { System.out.println("進1"); chain.invokeNext(req, res); System.out.println("出1"); } }).addFilter(new Filter() { public void doFilter(Request req, Response res, FilterChain chain) { System.out.println("進2"); chain.invokeNext(req, res); System.out.println("出2"); } }); chain.invoke(req, res); } }