責任鏈模式(chain of responsbility)
阿新 • • 發佈:2017-06-23
src private ons wan resp ring bject send 都是
責任鏈模式定義如下:
avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.Chain the receiving objects and pass the request along the chain until an object handles it.
(使得多個對象都有機會處理請求,從而避免了請求的發送者和接受者之間的耦合關系。將這些對象連成一條鏈,並沿著這條鏈條傳遞請求,直到有對象處理為止)
應用:
責任鏈模式的優點:
責任鏈模式非常顯著的優點是將請求和處理分開。請求者可以不用知道是誰處理的,處理者可以不用直到請求的全貌,兩者解耦和,提高系統靈活性。
責任鏈模式的缺點:
1、性能問題,每個請求都是從鏈頭遍歷到鏈尾,特別是鏈比較長的時候,性能問題非常顯著。
2、調試不方便,處理鏈中或許設計子遞歸,調試邏輯復雜。
使用意見:
給鏈設置一個最大長度,避免出現過長的鏈,使得性能最佳。
package chainOfResponsibility; public interface Handle { String doHandle(String str); }
packagechainOfResponsibility; import java.util.ArrayList; import java.util.List; public class HandleChain { private List<Handle> list = new ArrayList<Handle>(); public HandleChain addHandle(Handle e) { list.add(e); return this; } public String doHandle(String str){ String result= str; for (Handle handle : list) { result = handle.doHandle(result); } return result; } }
package chainOfResponsibility; public class LineHandle implements Handle{ @Override public String doHandle(String str) { return str.replaceAll("html", "wangye"); } }
package chainOfResponsibility; public class NameHandle implements Handle{ @Override public String doHandle(String str) { return str.replace("name", "nyx"); } }
package chainOfResponsibility; public class SexHandle implements Handle{ @Override public String doHandle(String str) { return str.replace("1", "男"); } }
package test; import chainOfResponsibility.HandleChain; import chainOfResponsibility.LineHandle; import chainOfResponsibility.NameHandle; import chainOfResponsibility.SexHandle; public class Main { public static void main(String[] args) { LineHandle lh = new LineHandle(); NameHandle nh = new NameHandle(); SexHandle sh = new SexHandle(); HandleChain hc = new HandleChain(); hc.addHandle(lh).addHandle(nh).addHandle(sh); String str = "--111---name---html--"; String res = hc.doHandle(str); System.out.println(res); } }
最後結果:
責任鏈模式(chain of responsbility)