责任链模式定义如下:
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); }
package chainOfResponsibility; 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); } }
最后结果:
时间: 2024-10-08 22:21:35